gpt4 book ai didi

xml - XSL 根据属性对元素进行排序,特定元素除外

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:29 25 4
gpt4 key购买 nike

我已经有一个 XSL,它根据属性值 @id 或 @category 对我的整个文档进行排序。现在我想通过定义永远不应排序的节点来增强它。

这是一个示例 XML:

<root>
[several levels of xml open]

<elemetsToBeSorted>
<sortMe id="8" />
<sortMe id="2" />
<sortMe id="4" />
</elemetsToBeSorted>

<elemetsNOTToBeSorted>
<dontSortMe id="5" />
<dontSortMe id="3" />
<dontSortMe id="2" />
</elemetsNOTToBeSorted>

[several levels of xml closing]
</root>

这是我的 XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes" />

<!-- Sort all Elements after their id or category -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()">
<xsl:sort select="@id" />
<xsl:sort select="@category" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>


<!-- Next two templates clean up formatting after sorting -->
<xsl:template match="text()[not(string-length(normalize-space()))]" />

<xsl:template match="text()[string-length(normalize-space()) > 0]">
<xsl:value-of select="translate(.,'&#xA;&#xD;', ' ')" />
</xsl:template>

预期输出:

<root>
[several levels of xml open]

<elemetsToBeSorted>
<sortMe id="2" />
<sortMe id="4" />
<sortMe id="8" />
</elemetsToBeSorted>

<elemetsNOTToBeSorted>
<dontSortMe id="5" />
<dontSortMe id="3" />
<dontSortMe id="2" />
</elemetsNOTToBeSorted>

[several levels of xml closing]
</root>

我怎样才能让我的 XSL 忽略“elementsNOTToBeSorted”?

编辑:我有数百个应该排序的元素,但只有少数元素(及其子元素)不应该排序。所以逻辑类似于“对除 a 和 b 之外的所有内容进行排序”

最佳答案

<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>

<!-- all elements except a few sort their children -->
<xsl:template match="*[not(self::elemetsNOTToBeSorted | self::otherElemetsNOTToBeSorted)]">
<xsl:copy>
<xsl:apply-templates select="@*" />
<xsl:apply-templates>
<xsl:sort select="@id" />
<xsl:sort select="@category" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>

<!-- ... -->

请注意,匹配表达式特异性在这里发挥作用。更具体的匹配表达式决定将运行哪个模板:

  • node()不如 * 具体, 因此元素节点将由 <xsl:template match="*"> 处理
  • 元素匹配self::elemetsNOTToBeSorted | self::otherElemetsNOTToBeSorted将由身份模板处理。

关于xml - XSL 根据属性对元素进行排序,特定元素除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12827419/

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