我想选择不带子节点的父节点。
示例:
<Shop>
<Product>
<ProductId>1</ProductId>
<Description>ProductList</Description>
<Milk>
<MilkId></MilkId>
</Milk>
</Product>
</Shop>
所需的输出:
<Shop>
<Product>
<ProductId>1</ProductId>
<Description>ProductList</Description>
</Product>
</Shop>
我在XSLT以下尝试过,但未能返回正确的结果:
<xsl:copy-of select="//Product/not[Milk]"/>
感谢您的帮助。
更新:
XSLT:
<xsl:copy-of select="Product/*[not(self::Milk)]" />
返回:
<ProductId>1</ProductId>
我需要返回以下结构:
<Shop>
<Product>
<ProductId>1</ProductId>
<Description>ProductList</Description>
</Product>
</Shop>
答案 0 :(得分:0)
您可以使用身份模板的一种变体:
<!-- Identity template variant -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()[local-name()!='Milk']|@*" />
</xsl:copy>
</xsl:template>
或者,作为注释中建议的XSLT-2.0的更多方式
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node() except Milk|@*" />
</xsl:copy>
</xsl:template>
它将复制除名为Milk
的节点及其子节点之外的所有节点。
如果仅要将其应用于Product
节点,则还必须使用身份模板并将匹配规则更改为
<xsl:template match="Product">...
仅使用xsl:copy-of
的解决方案可以复制Product
元素,然后使用以下方式复制其所有子元素(Milk
除外)
<xsl:copy-of select="Product/*[not(self::Milk)]" />
或者,在整个XSLT-2.0模板中
<xsl:template match="//Product">
<xsl:copy>
<xsl:copy-of select="* except Milk" />
</xsl:copy>
</xsl:template>
整个XSLT-1.0样式表可能看起来像
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<!-- Identity template -->
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*" />
</xsl:copy>
</xsl:template>
<xsl:template match="Product">
<xsl:copy>
<xsl:copy-of select="*[not(self::Milk)]" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
其输出是:
<?xml version="1.0"?>
<Shop>
<Product>
<ProductId>1</ProductId>
<Description>ProductList</Description>
</Product>
</Shop>