我想对xml
进行排序- 首先是标签名称,然后是
- 其每个属性名称,然后
- 属性值应排序
例如:
想先按其标签名称对XML进行排序,然后通过其属性名称,然后通过属性值进行排序。
例如对于以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<myroot>
<mychild id="123">
<fruit>apple</fruit>
<test hello="world" testing="removed" brackets="angled" question="answers"/>
<comment>This is a comment</comment>
</mychild>
<mychild id="789">
<fruit>orange</fruit>
<test brackets="round" hello="greeting">
<number>111</number>
</test>
<dates>
<modified>123</modified>
<created>880</created>
<accessed>44</accessed>
</dates>
</mychild>
<mychild id="456">
<fruit>banana</fruit>
<comment>This will be removed</comment>
</mychild>
</myroot>
XSLT应产生以下输出
<?xml version="1.0" encoding="UTF-8"?>
<myroot>
<mychild id="123">
<comment>This is a comment</comment>
<fruit>apple</fruit>
<test brackets="angled"
hello="world"
question="answers"
testing="removed"/>
</mychild>
<mychild id="456">
<comment>This will be removed</comment>
<fruit>banana</fruit>
</mychild>
<mychild id="789">
<dates>
<accessed>44</accessed>
<created>880</created>
<modified>123</modified>
</dates>
<fruit>orange</fruit>
<test brackets="round" hello="greeting">
<number>111</number>
</test>
</mychild>
</myroot>
我看到下面的xslt正在工作: - )
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output indent="yes" />
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
<xsl:sort select="." />
</xsl:apply-templates>
<xsl:apply-templates>
<xsl:sort select="name()"/>
<xsl:sort select="." />
<xsl:sort select="text()" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|comment()|processing-instruction()">
<xsl:copy />
</xsl:template>
</xsl:stylesheet>
此代码也将根据属性进行排序:
<?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>