加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何从xml中删除元素使用xslt with stylesheet和xsltproc?

发布时间:2020-12-16 08:14:56 所属栏目:百科 来源:网络整理
导读:我有很多XML文件,有一些形式: Element fruit="apple" animal="cat" / 其中我想从文件中删除。 使用XSLT样式表和Linux命令行实用程序xsltproc,我该怎么做? 到这一点,在脚本中我已经有包含我想要删除的元素的文件列表,所以单个文件可以用作一个参数。 编
我有很多XML文件,有一些形式:
<Element fruit="apple" animal="cat" />

其中我想从文件中删除。

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

到这一点,在脚本中我已经有包含我想要删除的元素的文件列表,所以单个文件可以用作一个参数。

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

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

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

请注意第二个模板如何仅覆盖名为“元素”的元素的元素,该元素具有值为“apple”的属性“fruit”和值为“cat”的属性“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找到。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读