Sort XML by attribute names using XSLT
Can any one please suggest how to sort an XML by attribute names using XSLT?
For example: my XML is as below
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!-- test 1 -->
<test g="r">
<a g="c" d="e">one</a>
<!-- a k z d b -->
<a k="z" d="b">two</a>
<a s="h" d="5">three</a>
<!-- a a b d 4 -->
<a a="b" d="4">four</a>
<a b="q" d="3">five</a>
<a s="a" d="8">3three</a>
<a x="i" d="2">six</a>
<!-- six 2 a f h i 2 -->
<a f="h" i="2">six</a>
<a l="t" d="1">seven</a>
</test>
<!-- test 2 -->
<test t="b">
<!-- six 2 a z i d 2 -->
<a z="i" d="2">six</a>开发者_运维知识库;
<a r="z" d="b">two</a>
<a a="c" d="e">one</a>
<a u="h" d="5">three</a>
<!-- four -->
<a c="b" d="4">four</a>
<a h="q" d="3">five</a>
<a p="t" d="1">seven</a>
</test>
</root>
expected output should be:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<!-- test 1 -->
<test g="r">
<!-- a a b d 4 -->
<a a="b" d="4">four</a>
<a b="q" d="3">five</a>
<a g="c" d="e">one</a>
<!-- six 2 a f h i 2 -->
<a f="h" i="2">six</a>
<!-- a k z d b -->
<a k="z" d="b">two</a>
<a l="t" d="1">seven</a>
<a s="a" d="8">3three</a>
<a s="h" d="5">three</a>
<a x="i" d="2">six</a>
</test>
<!-- test 2 -->
<test t="b">
<a a="c" d="e">one</a>
<!-- four -->
<a c="b" d="4">four</a>
<a h="q" d="3">five</a>
<a p="t" d="1">seven</a>
<a r="z" d="b">two</a>
<a u="h" d="5">three</a>
<!-- six 2 a z i d 2 -->
<a z="i" d="2">six</a>
</test>
</root>
I suspect you might be wanting it to sort on the name of the first attribute. That can't be done, because the order of attributes has no significance in XML, and you can't predict which attribute @*[1] will select.
<xsl:template match="test">
<xsl:apply-templates>
<xsl:sort select="@d"/>
</xsl:apply-templates>
</xsl:template>
will get you the elements under test
sorted by attribute d
.
You can do multiple sort-levels by adding another xsl:sort
.
More about sorting here: http://www.w3.org/TR/xslt#sorting
I found the solution myself.. Below is the line of code to be used for sorting by attribute names.
<xsl:sort select="local-name(@*)"/>
Guys, thanks for all your efforts.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
</xsl:apply-templates>
<xsl:apply-templates>
<xsl:sort select="name()"/>
<xsl:sort select= "name(@*)"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="@*">
<xsl:copy />
</xsl:template>
</xsl:stylesheet>
精彩评论