如何在xsl中使用self ::删除节点?

时间:2012-02-21 11:17:25

标签: xml xslt xpath

例如下面是xml

<products>
    <product>
        <name>Pen</name>
        <Quantity>2</Quantity>
        <Amount><Price>2</Price><Currency>USD</Currency></Amount>
    </product> 
    <product>
        <name>Pencil</name>
        <Quantity>20</Quantity>
        <Amount><Price>2</Price><Currency>USD</Currency></Amount>
    </product>
    <product>
        <name>Bag</name>
        <Quantity>25</Quantity>
        <Amount><Price>2</Price><Currency>USD</Currency></Amount>
    </product>
</products>

在我的xsl我用下面的方法删除

<xsl:copy-of select="node()[not(self::Quantity)]"/>

我还需要从<Currency>

中删除子节点<Amount>

我尝试如下

<xsl:copy-of select="node()[not(self::Quantity) and not(self::Amount/Currency)]"/>

但工作不正常。它将从<Amount>

中删除所有节点

我如何仅删除子节点<Currency>

1 个答案:

答案 0 :(得分:2)

如果您真的想使用self

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

或者如果您想了解其他更简单的方法:)

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
  <xsl:template match="Currency"/>

以上模板会复制除<Currency>

以外的所有其他标记
  

编辑:替换以下代码

<xsl:template match="product">
   <product>
    <xsl:for-each select="key('kProdByName', name)">
      <xsl:if test="position() = 1">
        <xsl:copy-of select="node()"/>
      </xsl:if>
    </xsl:for-each>
   </product>
</xsl:template>

通过这个:(希望它有效)

  <xsl:template match="product">
    <product>
      <xsl:for-each select="key('kProdByName', name)">
        <xsl:if test="position() = 1">
          <xsl:apply-templates select="node()|@*"/>
      </xsl:if>
      </xsl:for-each>
    </product>
  </xsl:template>

  <xsl:template match="Currency|Quantity"/>
相关问题