我想定义一个元素中使用的字符串的排序.例如,<class> Senior </ class> <class> Junior </ class> <class> Sophomore </ class> <class> Freshman <class>将描述类的合理排序.
有没有办法使用<xsl:sort select ='class'>按上面给出的顺序排序?
提前致谢.
您可以在XSLT中执行的操作是定义一个变量来表示您的自定义顺序,就像这样
<xsl:variable name="inline-array">
<class sort="1">Senior</class>
<class sort="2">Junior</class>
<class sort="3">Sophomore</class>
<class sort="4">Freshman</class>
</xsl:variable>
Run Code Online (Sandbox Code Playgroud)
然后,要访问此"数组",您可以定义另一个变量来引用XSLT文档本身:
<xsl:variable name="array"
select="document('')/*/xsl:variable[@name='inline-array']/*" />
Run Code Online (Sandbox Code Playgroud)
现在,您可以在排序时查找给定类名的sort属性(其中current()表示正在排序的当前节点)
<xsl:sort select="$array[. = current()/@class]/@sort" />
Run Code Online (Sandbox Code Playgroud)
例如,这是完整的XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:variable name="inline-array">
<class sort="1">Senior</class>
<class sort="2">Junior</class>
<class sort="3">Sophomore</class>
<class sort="4">Freshman</class>
</xsl:variable>
<xsl:variable name="array"
select="document('')/*/xsl:variable[@name='inline-array']/*"/>
<xsl:template match="/objects">
<xsl:copy>
<xsl:apply-templates select="object">
<xsl:sort select="$array[. = current()/@class]/@sort" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
当您将此应用于以下示例XML时...
<objects>
<object id="2" name="Junior Jo" class="Junior" />
<object id="1" name="Senior Sue" class="Senior" />
<object id="4" name="Freshman Frank" class="Freshman" />
<object id="3" name="Sophie Sophomore" class="Sophomore" />
</objects>
Run Code Online (Sandbox Code Playgroud)
返回以下内容
<objects>
<object id="1" name="Senior Sue" class="Senior"></object>
<object id="2" name="Junior Jo" class="Junior"></object>
<object id="3" name="Sophie Sophomore" class="Sophomore"></object>
<object id="4" name="Freshman Frank" class="Freshman"></object>
</objects>
Run Code Online (Sandbox Code Playgroud)