XSLT 按名称对节点进行排序? [英] XSLT to sort nodes by name?
问题描述
我不确定 xsl:sort
指令是如何工作的.我需要按标签名称对元素进行排序(用于差异化),但我似乎无法想出如何进行这项工作.我的第一个虽然是修改身份转换,只是修改它以包含一个排序语句,但我不确定如何做到这一点.
I'm unsure how the xsl:sort
directive works. I need to sort elements by their tag name (for diffing), and I can't seem to come up with how to make this work. My first though was to modify the identity transform and just modify it to include a sort statement, but I'm not exactly sure how to do that.
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()">
<!-- xsl:sort ? -->
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
推荐答案
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*">
<xsl:sort select="name()"/>
</xsl:apply-templates>
<xsl:apply-templates select="node()">
<xsl:sort select="name()"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
应用于此 XML 文档时:
<t b="x" c="y" a="t">
<c/>
<b/>
<a/>
</t>
产生想要的排序输出:
<t a="t" b="x" c="y">
<a></a>
<b></b>
<c></c>
</t>
请注意:
不仅对元素进行排序,而且对属性进行排序(后者依赖于实现,但适用于 MSXML).
Not only the elements but also the attributes are sorted (the latter is implementation dependent, but works OK with MSXML).
对差异使用排序的 XML 是不可靠的,因为将 XML 文档转换为排序的表示不是 1:1 映射.
Using sorted XML for diffs is unreliable, because converting an XML document to a sorted representation isn't 1:1 mapping.
这篇关于XSLT 按名称对节点进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!