xml - 过滤没有属性的元素,但使用 XSLT 保留包含其父元素的元素

标签 xml xslt

我正在尝试为包含特定属性的叶元素过滤 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/

相关文章:

c# - 如何抑制列表属性的 XML 标记

java web 应用程序和 xslt - 当 xml/xslt 文件更改时会发生什么?

xslt - 从 XSLT 调用 Java 函数给出 "Could not compile stylesheet"

xml - XSLT 处理元素的第一次出现

c# - Saxon 9 Compiled Transform 的线程安全

xml - 如何在元素中检测文本节点

python - XML 解析 - ElementTree vs SAX 和 DOM

php - 如何将 BitmapData 对象直接上传到我的服务器?

android - 如何在 Android 中解析 xml 类型的 HTTPResponse

java - 将 Activity 中定义的布局更改为 xml 布局