我正在尝试为包含特定属性的叶元素过滤 xml 文档,但我想保持更高级别的文档完整。我想用 XSLT 来做到这一点。
开始的文档如下所示:
<root>
<a name="foo">
<b name="bar" critical="yes"/>
</a>
<a name="foo2" critical="yes">
<b name="bar2">
<b name="bar3">
</a>
<a name="foo3">
<b name="bar4">
<b name="bar5">
</a>
</root>
结果应该是这样的:
<root>
<a name="foo">
<b name="bar" critical="yes"/>
</a>
<a name="foo2" critical="yes">
</a>
</root>
由于 XSLT 不是我的母语,因此非常感谢任何帮助。
最佳答案
这个转换:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(descendant-or-self::*[@critical='yes'])]"/>
</xsl:stylesheet>
应用于提供的 XML 文档时(针对格式正确性进行了更正):
<root>
<a name="foo">
<b name="bar" critical="yes"/>
</a>
<a name="foo2" critical="yes">
<b name="bar2"/>
<b name="bar3"/>
</a>
<a name="foo3">
<b name="bar4"/>
<b name="bar5"/>
</a>
</root>
产生想要的、正确的结果:
<root>
<a name="foo">
<b name="bar" critical="yes"/>
</a>
<a name="foo2" critical="yes"/>
</root>
关于xml - 过滤没有属性的元素,但使用 XSLT 保留包含其父元素的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12301215/