Reputation: 13
Sorting is giving me a hard time.
I need help with an small example, so that I can understand xsl:sort better.
My xml data looks as followed:
<NewTerms>
<newTerm>Zebra</newTerm>
<newTerm>Horse</newTerm>
<newTerm>Cat</newTerm>
<newTerm>Lion</newTerm>
<newTerm>Jaguar</newTerm>
<newTerm>Cheetah</newTerm>
<newTerm>Deer</newTerm>
<newTerm>Buffalo</newTerm>
<newTerm>Dog</newTerm>
</NewTerms>
and I just simply want to sort them alphabetically from a xsl sheet. The xsl that i have written (& which is not working) is as followed:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
<xsl:template match="NewTerms">
<xsl:apply-templates>
<xsl:sort select="newTerm"/>
</xsl:apply-templates>
</xsl:template>
</xsl:stylesheet>
I am very sure that I haven't understood how xsl:sort function.
Upvotes: 1
Views: 5439
Reputation: 1796
I assume you want a valid XML structure as output again because in your <xsl:output>
the method is "XML".
You could try this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xd="http://www.oxygenxml.com/ns/doc/xsl"
version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no" />
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()">
<xsl:sort select="."/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
which gives this output:
<?xml version="1.0" encoding="UTF-8"?>
<NewTerms>
<newTerm>Buffalo</newTerm>
<newTerm>Cat</newTerm>
<newTerm>Cheetah</newTerm>
<newTerm>Deer</newTerm>
<newTerm>Dog</newTerm>
<newTerm>Horse</newTerm>
<newTerm>Jaguar</newTerm>
<newTerm>Lion</newTerm>
<newTerm>Zebra</newTerm>
</NewTerms>
You could also look at the definition of sort,e.g.: http://www.w3schools.com/xsl/el_sort.asp http://www.w3.org/TR/xslt#sorting
Upvotes: 5
Reputation:
<xsl:template match="NewTerms"> <xsl:apply-templates> <xsl:sort select="newTerm"/> </xsl:apply-templates> </xsl:template>
I am very sure that I haven't understood how xsl:sort function
You are right. From http://www.w3.org/TR/xslt#sorting
xsl:sort
has aselect
attribute whose value is an expression. For each node to be processed, the expression is evaluated with that node as the current node and with the complete list of nodes being processed in unsorted order as the current node list.* The resulting object is converted to a string as if by a call to thestring
function; this string is used as the sort key for that node. The default value of theselect
attribute is.
, which will cause the string-value of the current node to be used as the sort key.
* Emphasis mine.
You want:
<xsl:template match="NewTerms">
<xsl:apply-templates>
<xsl:sort/>
</xsl:apply-templates>
</xsl:template>
Upvotes: 2