gpt4 book ai didi

xml - 使用 XSL 将 XML 节点替换为新节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:43:51 24 4
gpt4 key购买 nike

我需要一个 XSL 解决方案来用新节点替换 XML 节点。

假设我有以下现有的 XML 结构:

<root>
<criteria>
<criterion>AAA</criterion>
</criteria>
</root>

我想将一个标准节点替换为:

<criterion>BBB</criterion>
<criterion>CCC</criterion>
<criterion>DDD</criterion>

这样最终的XML结果就是:

<root>
<criteria>
<criterion>BBB</criterion>
<criterion>CCC</criterion>
<criterion>DDD</criterion>
</criteria>
</root>

我曾尝试使用 substring-before 和 substring-after 只复制结构的前半部分,然后只复制后半部分(以便在两半之间填充我的新节点)但看起来substring 函数只识别节点标签之间的文本,而不是像我希望的那样识别标签本身。 :( :(

还有其他解决方案吗?

最佳答案

XSL 不能替换任何东西。你能做的最好的事情就是复制你想保留的部分,然后输出你想改变的部分,而不是你不想保留的部分。


例子:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:output method="xml" indent="yes"/>

<!-- This is an identity template - it copies everything
that doesn't match another template -->
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

<!-- This is the "other template". It says to use your BBB-DDD elements
instead of the AAA element -->
<xsl:template match="criterion[.='AAA']">
<xsl:element name="criterion">
<xsl:text>BBB</xsl:text>
</xsl:element>
<xsl:element name="criterion">
<xsl:text>CCC</xsl:text>
</xsl:element>
<xsl:element name="criterion">
<xsl:text>DDD</xsl:text>
</xsl:element>
</xsl:template>
</xsl:stylesheet>

模板匹配@* | node() 匹配任何属性或任何其他类型的节点。诀窍是模板匹配有优先级。您可以将规则视为“更具体的比赛获胜”。 Anything 将比“任何属性或其他节点”更具体。这使得“身份”匹配的优先级非常低。

当它匹配时,它只是简单地复制它在匹配的属性或节点中找到的任何节点。

您拥有的任何其他模板都将具有更高的优先级。无论它们匹配什么,都是更具体的模板中的代码才会生效。例如,如果您只是简单地删除了 criterion[.='AAA'] 模板中的所有内容,您会发现除了“AAA”元素之外,您已经完全复制了您的输入。

关于xml - 使用 XSL 将 XML 节点替换为新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2952562/

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