XSLT:检查值是否为空然后删除标签

XSLT :Check if value is empty then remove the tag

我们有输入 XML。我们正试图删除那些具有空值和非空值的元素。我们有 <Item> 作为重复元素。 <TermsCode> 重复项具有空值和非空值。

如果它是空的,我们必须在检查 XSLT 后删除这样的 <TermsCode> 空标签。或者如果它有价值,它应该保留标签。 同样,我们正在尝试为项目节点中涉及的每个元素编写。如果它是空的,则删除。如果不是,则应将标签保留在输出 XML.

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

尝试过 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>

预期输出

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

删除空 TermsCode 元素:

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

要删除 Item 任何 个空子元素,更改:

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

至:

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