![](/img/trans.png)
[英]Remove all child nodes from the parent except one specific, an xml in c #
[英]Remove all nodes from an xml except for some
我有一个简单的xml文件,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<garbage1>something</garbage1>
<garbage2>something</garbage2>
<garbage3>something</garbage3>
<item>
<a>
<b/>
<c>123</c>
</a>
<d>456</d>
</item>
<item>
<a>
<b/>
<c>789</c>
</a>
<d>666</d>
</item>
</root>
我想删除<item>
节点内除<c>
和<d>
之外的所有节点,以得到如下结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item>
<c>123</c>
<d>456</d>
</item>
<item>
<c>789</c>
<d>666</d>
</item>
</root>
显然,执行此操作的正确方法是使用标识转换,然后相应地覆盖它。 如果我只想删除<c>
和<d>
,那么就可以了:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- identity transformation-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- override identity transformation-->
<xsl:template match="c|d"/>
</xsl:stylesheet>
好的,所以我只需要否定参数即可消除不是<c>
或<d>
的所有节点。 为什么这不起作用?
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- identity transformation-->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- override identity transformation to (apparently not) get rid of all nodes except 'c' and 'd'-->
<xsl:template match="//*[not(local-name() = ('c', 'd'))]"/>
</xsl:stylesheet>
非常感谢大家,我想在这里错过一些简单的事情...
首先,实现以下目标的正确方法:
删除
<item>
节点内除<c>
和<d>
以外的所有节点
是:
XSLT 1.0 / 2.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor::item][not(self::c or self::d)]">
<xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>
这匹配c
和d
之外的“ <item>
”之内的任何节点(即item
的后代),并将模板应用于其子节点,而不复制自身。 因此,例如,删除a
包装器-但其c
子级仍由身份转换模板处理。
您的尝试没有用,因为您的第二个模板已应用于root
元素。 从那里开始,模板没有输出任何内容,也没有应用任何其他模板-因此处理在该点结束,结果为空。
我找到了一种使用另一种方法解决此问题的方法:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="root">
<root>
<xsl:apply-templates select="@*|node()"/>
</root>
</xsl:template>
<xsl:template match="item">
<item>
<xsl:apply-templates select="@*|node()"/>
</item>
</xsl:template>
<xsl:template match="c | d">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
但是,这仍然使我感到困惑,我的最初想法出了什么问题,因此,如果有人可以帮助我,我将非常高兴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.