I'm new to XSLT and I can't resolve the following problem:
I have a xml file like this:
<root>
<subset>
<e id="A"></e>
<e id="C"></e>
</subset>
<data>
<info id="A" order="3" name="ANode"></info>
<info id="B" order="4" name="BNode"></info>
<info id="C" order="1" name="CNode"></info>
<info id="D" order="2" name="DNode"></info>
</data>
</root>
And I want to produce this:
<root>
<newnode id="C" order="1" name="CNode"></newnode>
<newnode id="A" order="3" name="ANode"></newnode>
</root>
As you can see the idea is to "complete" the subset of ids by retrieving the respe开发者_JAVA技巧ctive info, and sort them accordingly to their order specified on <data>
.
Notice that <data>
is supposed to have a lot of child nodes.
Also, I'm separating the nodes with the information on the <data>
element from the subsets of ids, because I will have many subsets and I don't want to have repeated information "everywhere".
Thanks in advance.
Cross-references ask for using keys:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes"/>
<xsl:key name="k1" match="info" use="@id"/>
<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates select="subset/e">
<xsl:sort select="key('k1', @id)/@order" data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="e">
<newnode id="{@id}" order="{key('k1', @id)/@order}" name="{key('k1', @id)/@name}"/>
</xsl:template>
</xsl:stylesheet>
That should do for the input sample you presented.
You could also key off of the subset depending upon what else you may need to do with your actual data.
<xsl:output indent="yes" />
<xsl:key name="subset" match="e" use="@id" />
<xsl:template match="/">
<root>
<xsl:for-each select="//info[count(key('subset',@id)[1]) > 0]">
<xsl:sort select="@order" data-type="number" />
<newnode id="{@id}" order="{@order}" name="{@name}" />
</xsl:for-each>
</root>
</xsl:template>
精彩评论