xslt基于属性的条带节点树

时间:2011-08-28 22:35:00

标签: xslt

我想使用xslt将xml文件转换为几乎相同的xml文件,但是根据属性去掉节点。如果节点具有属性,则其子节点不会复制到输出文件。例如,我想从以下xml文件中剥离“健康”属性为“not_really”的节点

这是要转换的xml

<diet>

  <breakfast healthy="very">
    <item name="toast" />
    <item name="juice" />
  </breakfast>

  <lunch healthy="ofcourse">
    <item name="sandwich" />
    <item name="apple" />
    <item name="chocolate_bar" healthy="not_really" />
    <other_info>lunch is great</other_info>
  </lunch>

  <afternoon_snack healthy="not_really" >
    <item name="crisps"/>
  </afternoon_snack>

  <some_other_info>
    <otherInfo>important info</otherInfo>
  </some_other_info>
</diet>

这是所需的输出

<?xml version="1.0" encoding="utf-8" ?>

<diet>

  <breakfast healthy="very">
    <item name="toast" />
    <item name="juice" />
  </breakfast>

  <lunch healthy="ofcourse">
    <item name="sandwich" />
    <item name="apple" />
    <other_info>lunch is great</other_info>
  </lunch>

  <some_other_info>
    <otherInfo>important info</otherInfo>
  </some_other_info>
</diet>

这是我尝试过的(没有成功:)

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()[@healthy=not_really]"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:0)

两个小问题:

  1. not_really应该在引号中,表示它是文本值。否则,它会将其评估为查找名为“not_really”的元素。
  2. 您的apply-templates正在选择@healthy值为“not_really”的节点,您希望相反。
  3. 对样式表应用了修补程序:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()[not(@healthy='not_really')]"/>
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    

    或者,您可以为具有@healthy='not_really'的元素创建一个空模板:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:output method="xml" indent="yes"/>
    
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="*[@healthy='not_really']"/>
    
    </xsl:stylesheet>