could you please help me on this one? I've been trying to merge 2 xml node based on key in xslt 1.0, but I'm not getting anywhere unfortunately.
This is the XML input:
<?xml version="1.0" encoding="UTF-8"?>
<csv>
<line>
<field>DE</field>
<field/>
<field>DE:STN</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
<line>
<field>DE</field>
<field>DE:MWST</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
<line>
<field>SI</field>
<field/>
<field>SI:MSPRS</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
<line>
<field>BE</field>
<field>BE:BTW</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
</csv>
And I should have the following XML output in merging the lines which have the same line/field[1] as key, but very important preserving the order of values for line/field[i] between the lines:
<?xml version="1.0" encoding="UTF-8"?>
<csv>
<line>
<field>DE</field>
<field>DE:MWST</field>
<field>DE:STN</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
<line>
<field>SI</field>
<field/>
<field>SI:MSPRS</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
<line>
<field>BE</field>
<field>BE:BTW</field>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
<field/>
</line>
</csv>
If you could please give me a hint on how to solve this it would be great:)! Thank you very much!
Try the following stylesheet. It uses the Muenchian method to group the line
s by the value of the first field
, then populates each field
with the value of the first field
of the group in the same position that has a string value.
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:key name="line" match="line" use="field[1]" />
<xsl:template match="/csv">
<xsl:copy>
<xsl:for-each select="line[count(. | key('line', field[1])[1]) = 1]">
<xsl:copy>
<xsl:variable name="current-group" select="key('line', field[1])" />
<xsl:for-each select="field">
<xsl:variable name="i" select="position()" />
<xsl:copy>
<xsl:value-of select="$current-group/field[$i][string()]"/>
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:for-each>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.