根据值列表对XSLT中的XML进行排序 [英] Sorting XML in XSLT based on a list of values
问题描述
我想用XSL转换对一个XML文件进行排序.
I'd like to sort one XML file with an XSL transformation.
<root>
<element>
<name>A</name>
</element>
<element>
<name>B</name>
</element>
<element>
<name>C</name>
</element>
</root>
必须按以下名称列表进行排序:C,A,B,以便生成的XML为:
Must be sorted by the following list of names: C, A, B so that the resulting XML is:
<root>
<element>
<name>C</name>
</element>
<element>
<name>A</name>
</element>
<element>
<name>B</name>
</element>
</root>
显然,要排序的值列表应该是非常动态的(XSLT的参数,另一个XML文件...). 您知道如何在XSLT中执行此操作吗?
Obviously the list of values to be sort on should be quite dynamic (parameter of the XSLT, another XML file...). Any idea how to do that in the XSLT ?
谢谢, 克里斯托夫(Christophe)
Thanks, Christophe
推荐答案
此转换:
<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:param name="pSortingValues" select="'C,A,B'"/>
<xsl:variable name="vSortingValues" select=
"concat(',', $pSortingValues, ',')"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="*">
<xsl:sort data-type="number" select=
"string-length(substring-before($vSortingValues,concat(',',name,',')))"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
应用于提供的XML文档:
<root>
<element>
<name>A</name>
</element>
<element>
<name>B</name>
</element>
<element>
<name>C</name>
</element>
</root>
产生想要的正确结果:
<root>
<element>
<name>C</name>
</element>
<element>
<name>A</name>
</element>
<element>
<name>B</name>
</element>
</root>
记录:
-
所需的排序值列表是
pSortingValues
全局参数,可以在转换外部提供.
The desired sorted values list is the
pSortingValues
global parameter, which can be provided externally to the transformation.
身份规则用于按原样复制所有节点.
顶部元素的标识规则已被覆盖.顶部元素被部分复制,其属性被复制,然后使用<xsl:sort>
子指令将模板应用于所有子元素,该子指令指定要使用的确切排序键-在pSortingValues
值前面如何element
子代的名称是.
The identity rule is overriden for the top element. The top element is partially copied, its attributes are copied, then templates are applied on all children-elements with an <xsl:sort>
child instruction, which specifies the exact sort key to be used -- how in front of the pSortingValues
values the name of the element
child is.
更新:如@Alejandro所述,
UPDATE: As noted by @Alejandro, this:
<xsl:sort data-type="number" select=
"string-length(substring-before($vSortingValues,concat(',',name,',')))"/>
可以简化为:
<xsl:sort data-type="number" select=
"substring-before($vSortingValues,concat(',',name,','))"/>
这篇关于根据值列表对XSLT中的XML进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!