gpt4 book ai didi

xslt - 您可以使用 XSLT 中的函数定义自定义排序规则吗?

转载 作者:行者123 更新时间:2023-12-05 00:32:17 25 4
gpt4 key购买 nike

我想为特定元素中使用的字符串定义一个顺序。比如 Senior Junior Sophomore Freshman 将描述类里面的合理排序。

有没有一种方法可以使用 按照上面给出的顺序进行排序?

提前致谢。

最佳答案

您可以在 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>

然后要访问这个“数组”,您可以定义另一个变量来引用 XSLT 文档本身:

<xsl:variable name="array" 
select="document('')/*/xsl:variable[@name='inline-array']/*" />

这现在允许您在排序时查找给定类名的 sort 属性(其中 current() 表示正在排序的当前节点)

<xsl:sort select="$array[. = current()/@class]/@sort" />

例如,这是完整的 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>

当您将其应用于以下示例 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>

返回以下内容

<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>

关于xslt - 您可以使用 XSLT 中的函数定义自定义排序规则吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7795474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com