XSLT convert xml to csv, transposing rows to colum

2019-08-29 08:33发布

问题:

I needed to use XSLT to generate CSV text output from XML

my XML

<Row> 
<cell>Currecy</cell>
<cell>RUR</cell>
<cell>USD</cell>
<cell>EURO</cell>
</Row> 
<Row> 
<cell>Param</cell>
<cell>17.2</cell>
<cell>12.12</cell>
<cell>100.2345</cell>
</Row> 
<Row> 
<cell>Param1</cell>
<cell>100</cell>
<cell>200</cell>
<cell>3556</cell>
</Row> 

output format CSV

Cur Param,  Param1
RUR, 17.2,  100     
USD, 12.12,  200
EURO, 100.2345, 3556

I do not know how to make a "transposition"

回答1:

If you had a valid XML input such as:

<Rows>
    <Row> 
        <cell>Currency</cell>
        <cell>RUR</cell>
        <cell>USD</cell>
        <cell>EURO</cell>
    </Row> 
    <Row> 
        <cell>Param</cell>
        <cell>17.2</cell>
        <cell>12.12</cell>
        <cell>100.2345</cell>
    </Row> 
    <Row> 
        <cell>Param1</cell>
        <cell>100</cell>
        <cell>200</cell>
        <cell>3556</cell>
    </Row> 
</Rows>

then you could use the following stylesheet:

XSLT 1.0

<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:for-each select="Rows/Row[1]/cell">
            <xsl:variable name="i" select="position()" />
                <xsl:for-each select="/Rows/Row">
                    <xsl:value-of select="cell[$i]"/>
                    <xsl:if test="position()!=last()">
                        <xsl:text>,</xsl:text>
                    </xsl:if>
                </xsl:for-each>
            <xsl:if test="position()!=last()">
                <xsl:text>&#10;</xsl:text>
            </xsl:if>
        </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

to obtain:

Currency,Param,Param1
RUR,17.2,100
USD,12.12,200
EURO,100.2345,3556