我想选择没有子节点的父节点。
例:
<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>
您可以使用标识模板的变体:
<!-- 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>