gpt4 book ai didi

xml - XSLT 将元素移动到另一个节点并在移动之前删除一些子元素

转载 作者:行者123 更新时间:2023-12-02 21:42:03 25 4
gpt4 key购买 nike

我有一个要求,需要将子节点从一个元素移动到另一个元素,并在复制之后/之前删除一些元素。尝试了 XSLT 的多种选项,但没有成功。

我的源 XML 如下

    <root>
<header>
<a1>Value1</a>
<a2>Value2</a2>
</header>
<body>
<b>
<c>
<d1>value3</d1>
<d2>value4</d2>
</c>
<!-- to be removed -->
<remove1>value4</remove1>
<remove2>value5</remove2>
</b>
</body>
</root>

预期输出是:

    <root>
<header>
<a1>Value1</a1>
<a2>Value2</a2>
<body>
<b>
<d1>value3</d1>
<d2>value4</d2>
</b>
</body>
</header>
</root>

我的 xslt 失败了

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" version="1.0" encoding="UTF-8"
indent="yes" />

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

<xsl:template match="/root/header/body/b/remove1" />
<xsl:template match="/root/header/body/b/remove2" />
<xsl:template match="header">
<xsl:copy>
<xsl:copy-of select="node()" />
<xsl:copy-of select="//body" />
</xsl:copy>
</xsl:template>

<xsl:template match="/root/body" />

</xsl:stylesheet>

你能帮我一下吗?

最佳答案

使用身份转换模板启动样式表代码

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

然后添加模板

<xsl:template match="c">
<xsl:apply-templates/>
</xsl:template>

确保 c 未被复制,但其子级被复制,并添加模板

<xsl:template match="remove1 | remove2"/>

删除元素(以抑制它们被复制)。

我将添加完整的示例:

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

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

<xsl:template match="c">
<xsl:apply-templates/>
</xsl:template>

<xsl:template match="remove1 | remove2"/>

</xsl:stylesheet>

改变

<root>
<header>
<a1>Value1</a1>
<a2>Value2</a2>
</header>
<body>
<b>
<c>
<d1>value3</d1>
<d2>value4</d2>
</c>
<!-- to be removed -->
<remove1>value4</remove1>
<remove2>value5</remove2>
</b>
</body>
</root>

进入

<root>
<header>
<a1>Value1</a1>
<a2>Value2</a2>
</header>
<body>
<b>

<d1>value3</d1>
<d2>value4</d2>

<!-- to be removed -->


</b>
</body>
</root>

关于xml - XSLT 将元素移动到另一个节点并在移动之前删除一些子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20251634/

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