3

我正在尝试为包含特定属性的叶元素过滤 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 不是我的母语,因此非常感谢任何帮助。

4

1 回答 1

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>
于 2012-09-06T14:32:13.790 回答