过滤没有属性的元素,但保留包含其父对象的元素与XSLT

时间:2012-09-06 13:28:24

标签: 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不是我的母语,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

此转化

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