gpt4 book ai didi

xml - 如何使用带有样式表和 xsltproc 的 xslt 从 xml 中删除元素?

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

我有很多具有以下形式的 XML 文件:

<Element fruit="apple" animal="cat" />

我想从文件中删除。

使用 XSLT 样式表和 Linux 命令行实用程序 xsltproc,我该怎么做?

此时在脚本中我已经有了包含我希望删除的元素的文件列表,因此可以将单个文件用作参数。


编辑:这个问题最初缺乏意图。

我想要实现的是删除整个元素“Element”,其中(fruit==“apple” && animal==“cat”)。在同一文档中有许多名为“Element”的元素,我希望保留这些元素。所以

<Element fruit="orange" animal="dog" />
<Element fruit="apple" animal="cat" />
<Element fruit="pear" animal="wild three eyed mongoose of kentucky" />

会变成:

<Element fruit="orange" animal="dog" />
<Element fruit="pear" animal="wild three eyed mongoose of kentucky" />

最佳答案

使用最基本的 XSLT 设计模式之一:“覆盖 identity transformation”,只需编写以下内容:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes"/>    <xsl:template match="node()|@*">      <xsl:copy>         <xsl:apply-templates select="node()|@*"/>      </xsl:copy>    </xsl:template>    <xsl:template match="Element[@fruit='apple' and @animal='cat']"/></xsl:stylesheet>

请注意第二个模板如何仅针对名为“Element”的元素覆盖标识(第一个)模板,这些元素的属性“fruit”的值为“apple”,属性“animal”的值为“猫”。这个模板有空主体,这意味着匹配的元素被简单地忽略(匹配时不产生任何东西)。

当此转换应用于以下源 XML 文档时:

<doc>...     <Element name="same">foo</Element>...    <Element fruit="apple" animal="cat" />    <Element fruit="pear" animal="cat" />    <Element name="same">baz</Element>...    <Element name="same">foobar</Element>...</doc>

产生了想要的结果:

<doc>...     <Element name="same">foo</Element>...    <Element fruit="pear" animal="cat"/>    <Element name="same">baz</Element>...    <Element name="same">foobar</Element>...</doc>

可以找到更多使用和覆盖身份模板的代码片段 here .

关于xml - 如何使用带有样式表和 xsltproc 的 xslt 从 xml 中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/321860/

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