如果子节点为空,则删除父节点 [英] Remove parent node if a child node is empty
本文介绍了如果子节点为空,则删除父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
源 XML:
<MP>
<Name>pol</Name>
<PRules>
<PRule order="1" name="r1">
<Conditions>
<Condition eleName="eth" value="05">05</Condition>
<Condition eleName="dest" value="32">32</Condition>
</Conditions>
</PRule>
<PRule order="2" name="r2">
<Conditions>
<Condition eleName="eth" value="04">04</Condition>
</Conditions>
<Actions>
<Action name="xyz"/>
</Actions>
</PRule>
</PRules>
</MP>
如果必须删除具有属性 eleName="eth" 的 Condition 节点.如果 Condition 为空,则删除 Condition 节点后,还必须删除完整的 PRule 节点.
If a Condition node with attribute eleName="eth" has to be deleted. After deletion of Condition node if Conditions is empty, complete PRule node also has to be removed.
我已应用以下 XSLT:
I have applied the following XSLT:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template name="attributeTemplate" match="Condition[@elementName='eth']"/>
<xsl:template match="PRule[descendant::Conditions[not(@*)]]"/>
</xsl:stylesheet>
但结果是这样的:
<MP>
<Name>pol</Name>
</PRules>
</MP>
我必须做哪些更改才能将 XML 转换为
What change I have to make to transform the XML as
<MP>
<Name>pol</Name>
<PRules>
<PRule name="r1" order="1">
<Conditions>
<Condition eleName="dest" value="32">32</Condition>
</Conditions>
</PRule>
</PRules>
</MP>
xsl 文件出了什么问题,我不明白.基本上,如果条件为空,我想删除父 PRule 节点.
What went wrong in xsl file, I don't understand. Basically I wanted remove the parent PRule node if Conditions is empty.
推荐答案
这种转变:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="PRule[not(*/Condition[not(@eleName='eth')])]"/>
<xsl:template match="Condition[@eleName = 'eth']"/>
</xsl:stylesheet>
应用于提供的 XML 文档时:
<MP>
<Name>pol</Name>
<PRules>
<PRule order="1" name="r1">
<Conditions>
<Condition eleName="eth" value="05">05</Condition>
<Condition eleName="dest" value="32">32</Condition>
</Conditions>
</PRule>
<PRule order="2" name="r2">
<Conditions>
<Condition eleName="eth" value="04">04</Condition>
</Conditions>
<Actions>
<Action name="xyz"/>
</Actions>
</PRule>
</PRules>
</MP>
产生想要的、正确的结果:
<MP>
<Name>pol</Name>
<PRules>
<PRule order="1" name="r1">
<Conditions>
<Condition eleName="dest" value="32">32</Condition>
</Conditions>
</PRule>
</PRules>
</MP>
说明:
Proper use of the identity rule and the double negation law.
这篇关于如果子节点为空,则删除父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文