我想把它从文件中删除。使用XSLT样式表和Linux命令行实用程序xsltproc,我该如何做呢?至此,在脚本中,我已经有了包含我希望删除的元素的文件列表,因此可以将单个文件用作参数。编辑:这个问题最初是缺乏意图的。我想要实现的是删除整个元素" element“where (猫”frui">
我有很多XML文件,它们的形式如下:
<Element fruit="apple" animal="cat" />
我想把它从文件中删除。
使用XSLT样式表和Linux命令行实用程序xsltproc,我该如何做呢?
至此,在脚本中,我已经有了包含我希望删除的元素的文件列表,因此可以将单个文件用作参数。
编辑:这个问题最初是缺乏意图的。
我想要实现的是删除整个元素" element“where (猫”fruit==“&& 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" />
发布于 2019-03-08 21:53:58
@Dimitre Novatchev给出的答案当然既正确又优雅,但有一个泛化( OP没有询问):如果您想要过滤的元素也有您想要保留的子元素或文本,该怎么办?
我认为这个小的变化涵盖了这种情况:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="2.0">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<!-- drop DropMe elements, keeping child text and elements -->
<xsl:template match="DropMe">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
要指定其他属性等,匹配条件可能很复杂,如果您要删除其他内容,则可以使用多个这样的模板。
所以这个输入:
<?xml version="1.0" encoding="UTF-8"?>
<mydocument>
<p>Here's text to keep</p>
<p><DropMe>Keep this text but not the element</DropMe>; and keep what follows.</p>
<p><DropMe>Also keep this text and <b>this child element</b> too</DropMe>, along with what follows.</p>
</mydocument>
生成以下输出:
<?xml version="1.0" encoding="UTF-8"?><mydocument>
<p>Here's text to keep</p>
<p>Keep this text but not the element; and keep what follows.</p>
<p>Also keep this text and <b>this child element</b> too, along with what follows.</p>
</mydocument>
归功于XSLT Cookbook。
https://stackoverflow.com/questions/321860
复制