首页 > 解决方案 > 删除满足条件的节点,如果为空则删除父节点

问题描述

我正在尝试删除所有满足条件的元素节点,然后删除父节点(如果它仍然没有子节点)。

我成功删除了所有满足我条件的孩子,但不知道如何删除父母如果它仍然是空的。

<root>
  <parent>
     <childA>
        <grandchildX>03</grandchildX>
        <grandchildY>02</grandchildY>
     </childA>
  </parent>
</root>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="childA[grandchildX[text()='03']][grandchildY[text()='02']]"/>

</xsl:stylesheet>

XSLT 样式表必须<parent>在它有其他子项时输出<childA>(例如<childB>)(这已经有效)。

标签: xmlxslt

解决方案


使用 XSLT 3(并假设xsl:strip-space),您可以xsl:where-populated在模板中使用parent

  <xsl:template match="parent">
      <xsl:where-populated>
          <xsl:next-match/>
      </xsl:where-populated>
  </xsl:template>

完整的样式表将是

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template match="childA[grandchildX[text()='03']][grandchildY[text()='02']]"/>

  <xsl:template match="parent">
      <xsl:where-populated>
          <xsl:next-match/>
      </xsl:where-populated>
  </xsl:template>

</xsl:stylesheet>

在https://xsltfiddle.liberty-development.net/ej9EGdh上使用 Saxon 9.8 HE 的在线示例。

对于 XSLT 1,我认为您可以尝试使用空模板

<xsl:template match="parent[childA[grandchildX[. = '03']][grandchildY[. ='02']] and not(*[not(self::childA[grandchildX[. = '03']][grandchildY[. ='02']])])]"/>

即完整的代码是

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="childA[grandchildX[. = '03']][grandchildY[. ='02']]"/>

    <xsl:template match="parent[childA[grandchildX[. = '03']][grandchildY[. ='02']] and not(*[not(self::childA[grandchildX[. = '03']][grandchildY[. ='02']])])]"/>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ej9EGdh/1


推荐阅读