xslt, how to 'flatten' the tag structure for unknown number of child tags
My source file looks like this:
<x>
<names&开发者_如何学编程gt;
<name>name1</name>
<name>name2</name>
</names>
<codes>
<code>code1</code>
<code>code2</code>
</codes>
<stuff> stuff </stuff>
</x>
And I'd like to transform it to get this output:
<out>
<y>
<name>name1</name>
<code>code1</code>
<stuff> stuff </stuff>
</y>
<y>
<name>name2</name>
<code>code2</code>
<stuff> stuff </stuff>
</y>
</out>
I don't know the number of name and code tags in source file, but I do know the numer of names equals number of codes.
Please share some tips, how to do it.
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<out>
<xsl:apply-templates select="names/name"/>
</out>
</xsl:template>
<xsl:template match="name">
<xsl:variable name="vPos" select="position()"/>
<y>
<xsl:copy-of select="."/>
<xsl:copy-of select=
"../../codes/code[position()=$vPos]"/>
<xsl:copy-of select="/*/stuff"/>
</y>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<x>
<names>
<name>name1</name>
<name>name2</name>
</names>
<codes>
<code>code1</code>
<code>code2</code>
</codes>
<stuff> stuff </stuff>
</x>
produces the wanted, correct result:
<out>
<y>
<name>name1</name>
<code>code1</code>
<stuff> stuff </stuff>
</y>
<y>
<name>name2</name>
<code>code2</code>
<stuff> stuff </stuff>
</y>
</out>
精彩评论