简体   繁体   中英

Remove element based on child element value with XSLT

After reading this answer and also this one I'm still quit confused how to remove an element (parent) based on another element (child) value. This is the example xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Order>
    <Orderline>
        <Itemcode>ABC</Itemcode>
        <Qty>0</Qty>
    </Orderline>
    <Orderline>
        <Itemcode>XYZ</Itemcode>
        <Qty>3</Qty>
    </Orderline>
    <Orderline>
        <Itemcode>DFG</Itemcode>
        <Qty>0</Qty>
    </Orderline>
</Order>

This is the XLST I currently have:

<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=
 "*[Qty='0']/Itemcode | *[Qty='0']/Qty "/>
</xsl:stylesheet>

Which produces this result:

 <Order>
    <Orderline/>
    <Orderline>
        <Itemcode>XYZ</Itemcode>
        <Qty>3</Qty>
    </Orderline>
    <Orderline/>
</Order>

How can you remove the empty <Orderline/> element as well? The idea is to remove <Orderline> , <Itemcode> and <Qty> elements if value of Qty = 0

This:

<xsl:template match="*[Qty='0']/Itemcode | *[Qty='0']/Qty "/>

matches either Itemcode or Qty , so those are the nodes that end up removed. In order to remove the entire Orderline with all its descendants, you only have to do:

<xsl:template match="Orderline[Qty='0']"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM