user972255
user972255

Reputation: 1828

XML to CSV using XSL transformation

I have a XML data and I need to convert the same to CSV using xsl transformation. But the problem is, the XML rootnodes (refer to A, B, C nodes) varies. Please see below:

XML data
--------
<Sheets>
<A>
<Data>
<Row>
<value1>2</value1>
<value2>4</value2>
</Row>
<Row>
<value1>5</value1>
<value2>6</value2>
</Row>   
</Data>
</A>
<B>
<Data>
<Row>
<value1>12</value1>
<value2>13</value2>
</Row>
<Row>
<value1>14</value1>
<value2>15</value2>
</Row>
</Data>
</B>
<C>
<Data>
<Row>
<value1>1</value1>
<value2>1</value2>
</Row>
<Row>
<value1>2</value1>
<value2>2</value2>
</Row>
</Data>
</C>
</Sheets>    
    CSV output should like this:
    ----------------------------
    A, 2, 4
    A, 5, 6
    B, 12, 13
    B, 14, 15
    C, 1, 1
    C, 2, 2

Please help me.

Thanks in advance.

Upvotes: 2

Views: 1544

Answers (2)

Tom Howard
Tom Howard

Reputation: 6687

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

    <xsl:template match="/Sheets">
        <xsl:for-each select="*">
            <xsl:variable name="dataSet" select="name()" />
            <xsl:for-each select="Data/Row">
                <xsl:value-of select="$dataSet" />
                <xsl:text>, </xsl:text>
                <xsl:for-each select="*">
                    <xsl:value-of select="text()" />
                    <xsl:if test="position() != last()">
                        <xsl:text>, </xsl:text>
                    </xsl:if>
                </xsl:for-each>
                <xsl:text>
</xsl:text>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 3

user1046285
user1046285

Reputation:

This should output the text you want:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/Sheets">
<!-- This will match the letters -->
<xsl:for-each select="*">
<xsl:for-each select="*/descendant::Row">
<xsl:text>
</xsl:text>
<!-- Name of grand parent (two levels up) which is the letter -->
<xsl:value-of select="local-name(../..)"/><xsl:for-each select="*">, <xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions