Reputation: 3
I'm new to XSLT 2.0 and I have to transform XML into a text file (CSV), but I want the output to be in the line attribute order (see below the XML, the stylesheet and the output). As you can see the output of line="9" should be the 2nd line. The question is how can I change the stylesheet to achieve the right output?
<?xml version="1.0" encoding="UTF-8"?>
<root>
<MP>
<CSVIMP line="10" content="xyz"/>
<CSVIMP line="11" content="123"/>
<CSVIMP line="8" content="123"/>
</MP>
<MP>
<CSVIMP line="9" content="abc"/>
<CSVIMP line="12" content="456"/>
</MP>
</root>
My stylesheet:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="text" encoding="UTF-8" />
<xsl:variable name="delimiter" select="','"/>
<xsl:template match="MP">
<xsl:for-each select="CSVIMP">
<xsl:sort select="./@line" data-type="number"></xsl:sort>
<xsl:value-of select="./@line"/>
<xsl:value-of select="$delimiter"/>
<xsl:value-of select="./@content"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()"></xsl:template>
</xsl:transform>
Transformed output (Saxon 9.5 HE):
8,123
10,xyz
11,123
9,abc
12,456
Upvotes: 0
Views: 172
Reputation: 116959
Hard to tell exactly what you want without seeing the expected output. Since you say that "the output of line="9" should be the 2nd line, I guess you want to do this (and only this):
<xsl:template match="/root">
<xsl:for-each select="MP/CSVIMP">
<xsl:sort select="./@line" data-type="number"></xsl:sort>
<xsl:value-of select="./@line"/>
<xsl:value-of select="$delimiter"/>
<xsl:value-of select="./@content"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
And since you're using XSLT 2.0, you could probably* shorten the whole thing to:
XSLT 2.0
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" />
<xsl:template match="/root">
<xsl:for-each select="MP/CSVIMP">
<xsl:sort select="./@line" data-type="number"/>
<xsl:value-of select="@line, @content" separator=","/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
(*) assuming all CSVIMP
elements have both attributes.
Upvotes: 1