sorting - XSLT sort by tag name and attribute value -
i'm noob xslt, please excuse ignorance... i'm trying sort simple xml file attribute value , tag name, struggle in accessing value of attribute. here complete example:
<a> <b attribute="e"></b> <b attribute="b"></b> <d attribute="a"></d> <c></c> </a>
and expected result is:
<a> <b attribute="b"></b> <b attribute="e"></b> <c></c> <d attribute="a"></d> </a>
here attempt solve this:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output indent="yes" /> <xsl:strip-space elements="*" /> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="@*"> <xsl:sort select="."/> </xsl:apply-templates> <xsl:apply-templates select="node()"> <xsl:sort select="name()"/> </xsl:apply-templates> </xsl:copy> </xsl:template> </xsl:stylesheet>
and don't work @ all...
in above example want sort b tag attribute value can see d tag not sorted attribute value because it's tag name...
i wonder if possible using xslt... have idea?
thanks in advance.
update----------------------
i tried andyb solution seems work fine , looks pretty simple, have issue solution.
let's have xml:
<a> <b attribute="e" optionalattr="fg"></b> <b attribute="b"></b> <d attribute="a"></d> <c></c> </a>
i added optional parameter b tag. applying andyb solution optional parameter ignored, because not matched in template. here result:
<a> <b attribute="b"></b> <b attribute="e"></b> <c></c> <d attribute="a"></d> </a>
instead of following expect:
<a> <b attribute="b"></b> <b attribute="e" optionalattr="fg"></b> <c></c> <d attribute="a"></d> </a>
do have idea? in advance.
you can use multiple xsl:sort
instructions, example:
<xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"> <xsl:sort select="name()" /> <xsl:sort select="@*" /> </xsl:apply-templates> </xsl:copy> </xsl:template>
and since default data-type "text" , default order "ascending" gives desired output.
edit
this strange, because following xml:
<a> <b attribute="e" optionalattr="fg"></b> <b attribute="b"></b> <d attribute="a"></d> <c></c> </a>
and xsl above, result:
<a> <b attribute="b"></b> <b attribute="e" optionalattr="fg"></b> <c></c> <d attribute="a"></d> </a>
this includes desired optional attribute order different xml in edited question (<c></c>
in different position).
Comments
Post a Comment