XSLT recursive sort by attribute
I found multiple questions and answers regarding nested/recursive sort using XSLT, but was not able to map it on my situation.
My situation:
- "set" element can consist of 0 or more "property" elements
- a "set" element can consist of 0 or more subsets
- both set and property elements consist of attribute "key"
- I want to sort the "set"s by "key" attribute, and per "set": sort by "k开发者_JAVA技巧ey" of "properties" elements
The XML looks something like:
<set key="...">
<property key="..."/>
<property key="..."/>
<property key="..."/>
<set key="...">
<set key="...>
<property key="..."/>
<property key="..."/>
<property key="..."/>
</set>
</set>
</set>
Suggestions?
In simple situations it can be achieved like this:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()">
<xsl:sort select="@key" data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Applied to this XML:
<set key="1">
<property key="6"/>
<property key="8"/>
<property key="1"/>
<set key="3">
<set key="0">
<property key="4"/>
<property key="2"/>
<property key="9"/>
</set>
</set>
</set>
Result will be:
<set key="1">
<property key="1"></property>
<set key="3">
<set key="0">
<property key="2"></property>
<property key="4"></property>
<property key="9"></property>
</set>
</set>
<property key="6"></property>
<property key="8"></property>
</set>
I guess real-life app is more complex, but your example doesn't show that.
Personally, I don't think XSL-T is suited for this sort of thing. It's an XML transformation language, not a programming language for sorting.
I think it'd be better to use the right tool for the job: Use a language like Java or C# to produce the XML in sorted form, then use XSL-T to transform it.
If you're struggling with it, you probably should re-think the approach.
精彩评论