如果子节点为空,则删除父节点

时间:2012-07-18 11:08:01

标签: xslt

源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节点。删除条件节点后如果条件为空,则还必须删除完整的PRule节点。

我已应用以下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转换为

<MP>
 <Name>pol</Name>
 <PRules>
  <PRule name="r1" order="1">
   <Conditions>
    <Condition eleName="dest" value="32">32</Condition>
   </Conditions>
  </PRule>
 </PRules>
</MP>

xsl文件出了什么问题,我不明白。基本上我想在条件为空时删除父PRule节点。

1 个答案:

答案 0 :(得分:3)

此转化

<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>

<强>解释

正确使用 identity rule double negation law