XML到CSV的转换

时间:2014-03-19 09:50:24

标签: xslt

我有一个场景,我需要将输入XML转换为CSV文件。输出应该具有每个属性的值以及它们各自的XPATH。 例如:如果我的输入是

<School>
    <Class>
        <Student name="" class="" rollno="" />
        <Teacher name="" qualification="" Employeeno="" />
    </Class>
</School>

预期输出为:

School/Class/Student/name, School/Class/Student/class, School/Class/Student/rollno, 
School/Class/Teacher/name, School/Class/Teacher/qualification, School/Class/Teacher/Employeeno  

1 个答案:

答案 0 :(得分:2)

一个例子并不总是体现一个规则。假设您希望每个具有任何属性的元素都有一行,无论它在文档中的哪个位置,以及元素的每个属性的列,请尝试:


编辑:

这是一个改进版本,已更正为嵌套元素正常工作。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text" encoding="UTF-8"/>

<xsl:template match="*">
    <xsl:param name="path" />
    <xsl:variable name="newpath" select="concat($path, '/', name())" />
    <xsl:apply-templates select="@*">
        <xsl:with-param name="path" select="$newpath"/>
    </xsl:apply-templates>
    <xsl:if test="@*">
        <xsl:text>&#10;</xsl:text>
    </xsl:if>
    <xsl:apply-templates select="*">
        <xsl:with-param name="path" select="$newpath"/>
    </xsl:apply-templates>
</xsl:template>

<xsl:template match="@*">
    <xsl:param name="path" />
    <xsl:value-of select="substring(concat($path, '/', name()), 2)"/>
    <xsl:if test="position()!=last()">
        <xsl:text>, </xsl:text>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

当应用于以下测试输入时:

<Root>
    <Parent parent="1" parent2="1b">
        <Son son="11" son2="11b"/>
        <Daughter daughter="12" daughter2="12b">
            <Grandson grandson="121" grandson2="121b"/>
            <Granddaughter granddaughter="122" granddaughter2="122b"/>
        </Daughter>
        <Sibling/>
    </Parent>
</Root>

结果是:

Root/Parent/parent, Root/Parent/parent2
Root/Parent/Son/son, Root/Parent/Son/son2
Root/Parent/Daughter/daughter, Root/Parent/Daughter/daughter2
Root/Parent/Daughter/Grandson/grandson, Root/Parent/Daughter/Grandson/grandson2
Root/Parent/Daughter/Granddaughter/granddaughter, Root/Parent/Daughter/Granddaughter/granddaughter2

请注意,每行中的列数可能会有所不同 - 这在CSV文档中通常是不可接受的。