I have a huge configuration file in XML format. The system does not care about the order of tags, but we humans do! (First of all, to compare versions.) I already got XSLT, below which it works well, but I found that this is not enough.
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates> <xsl:sort select="(@name, name())[1]"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
I want to sort all tags recursively by the value of their name attribute (this works!), But since the attribute is not always present, it must also sort by additional attributes, any of which may or may not be present in any particular element.
I basically have zero understanding of XSLT, so I'm experimenting. I hacked above, but this does not work as desired. The result of this seems to be identical to the one above.
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="*"> <xsl:copy> <xsl:copy-of select="@*"/> <xsl:apply-templates> <xsl:sort select="@name"/> <xsl:sort select="@row" data-type="number"/> <xsl:sort select="@col" data-type="number"/> <xsl:sort select="@sequence" data-type="number"/> <xsl:sort select="@tabindex" data-type="number"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
My data looks like this, and the problem is that the cell elements are not sorted at all (inside their grid group), because they do not have a name attribute. This is why I would like to extend the sorting logic to use the name attribute, if present, otherwise the sorting should be done using additional attributes like tabindex . Within any group, it can be considered that the same attributes are present.
<sections> <section name="SomeList"> <caption> <![CDATA[Candidates]]> </caption> ... <parameters> <parameter name="pageSize"> <![CDATA[50]]> </parameter> </parameters> ... <grid> <cell row="0" col="7" tabindex="9" colspan="10"> <field name="Entered" /> </cell> </grid> </section> </sections>
Update:
With Vincent very good help, I created a sort that works well enough for our purposes. Here he is.
Torben gundtofte-bruun
source share