0
votes

We have Input XML. We are trying to remove such elements those are having empty and non-empty values. we have <Item> as repeated element. <TermsCode> is having empty and non-empty values for repeated item.

We have to remove such <TermsCode> empty tag after making check in XSLT IF it is empty. or if it is having value it should keep the tag. Similarly, we are trying to write for each element involves in item node. if it is empty then remove. if not then should keep the tag in Output XML.

INPUT XML

<?xml version="1.0" encoding="UTF-8"?>
<SetupArCustomer>
   <Item>
      <Key>
         <Customer>0039069</Customer>
      </Key>
      <Name>ABC SOLUTIONS LLC</Name>
      <CreditLimit>0.0</CreditLimit>
      <PriceCode>WH</PriceCode>
      <Branch>NY</Branch>
      <TermsCode>00</TermsCode>
      </Item>
   <Item>
      <Key>
         <Customer>0039070</Customer>
      </Key>
      <Name>CCD WHOLESALE NY INC.</Name>
      <CreditLimit>0.0</CreditLimit>
      <PriceCode>HY</PriceCode>
      <Branch>NY</Branch>
      <TermsCode/>
     </Item>
   </SetupArCustomer>

TRIED XSLT2.0

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="Windows-1252" indent="yes" />
  <xsl:template xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" match="@xsi:nil[.='true']" />
  <xsl:template match="@*|node()">
    <xsl:copy copy-namespaces="no">
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Expected Output

<?xml version="1.0" encoding="UTF-8"?>
    <SetupArCustomer>
       <Item>
          <Key>
             <Customer>0039069</Customer>
          </Key>
          <Name>ABC SOLUTIONS LLC</Name>
          <CreditLimit>0.0</CreditLimit>
          <PriceCode>WH</PriceCode>
          <Branch>NY</Branch>
          <TermsCode>00</TermsCode>
          </Item>
       <Item>
          <Key>
             <Customer>0039070</Customer>
          </Key>
          <Name>CCD WHOLESALE NY INC.</Name>
          <CreditLimit>0.0</CreditLimit>
          <PriceCode>HY</PriceCode>
          <Branch>NY</Branch>
         </Item>
       </SetupArCustomer>
1

1 Answers

1
votes

To remove empty TermsCode elements:

<xsl:stylesheet version="2.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="TermsCode[not(node())]"/>

</xsl:stylesheet>

To remove any empty child element of Item, change:

<xsl:template match="TermsCode[not(node())]"/>

to:

<xsl:template match="Item/*[not(node())]"/>