My input is some unsorted XML, and I want to sort it – first alphabetically by I’m running into an issue when attempting to sort XML files with XSL. I want to sort through any number of nested nodes, first alphabetically by node, and then alphabetically by the text values as needed.
I’m having issues with “list” items consistently ordering. In my example below, it seems that sometimes it will order the two book items based on the title, whereas other times it will be done based on the author. I assume this has something to do with how the XML is ordered on input, but I have no knowledge of how this will come in.
I don’t care which book item comes first, only that it happens with consistency. Also, I want this to work generically. The list could be movies instead, or could be nested much deeper.
Example Input:
<root>
<nodeA>text</nodeA>
<nodeC>text</nodeC>
<nodeB>text</nodeB>
<bookList>
<book>
<title>ABC</title>
<author>John</author>
</book>
<book>
<title>XYZ</title>
<author>Dan</author>
</book>
</bookList>
</root>
Stylesheet:
<xsl:stylesheet version="1.0 xmlns:xsl-"http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates>
<xsl:sort select="name()"/>
<xsl:sort select="."/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Example Ouptut #1:
<root>
<bookList>
<book>
<title>ABC</title>
<author>John</author>
</book>
<book>
<title>XYZ</title>
<author>Dan</author>
</book>
</bookList>
<nodeA>text</nodeA>
<nodeB>text</nodeB>
<nodeC>text</nodeC>
</root>
Example Ouptut #2:
<root>
<bookList>
<book>
<title>XYZ</title>
<author>Dan</author>
</book>
<book>
<title>ABC</title>
<author>John</author>
</book>
</bookList>
<nodeA>text</nodeA>
<nodeB>text</nodeB>
<nodeC>text</nodeC>
</root>
As mentioned above, I’m fine with either output but I need it to work consistently with any order of input.
OreganoGo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.