mitch_au
mitch_au

Reputation: 323

Removing any element with a certain value from XML using XSLT

Using a transform I've found here on Stack Overflow, I'm able to remove empty tags from my XML using XSLT:

<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=
    "*[not(@*|*|comment()|processing-instruction())
     and normalize-space()=''
     ]"/>
</xsl:stylesheet>

My question is: How would I go about removing any elements with a particular value? e.g. my XML also has default blank values like :

          <BIRTHDATE>0000-00-00</BIRTHDATE>
          <DEATHDATE>0000-00-00</DEATHDATE>

I've seen examples that remove one particular element with a certain value, but how can I match any element with a certain value?

Upvotes: 1

Views: 1099

Answers (2)

kjhughes
kjhughes

Reputation: 111726

Simply use the identify transformation plus a null override for elements whose string value matches the string you wish to remove ("0000-00-00"):

<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="*[ not(*) and . = '0000-00-00']"/>

</xsl:stylesheet>

Upvotes: 3

har07
har07

Reputation: 89325

Part that indicates empty value is and normalize-space()='', you can modify that part to match empty or particular value like so :

<xsl:template match=
    "*[not(@*|*|comment()|processing-instruction())
     and (normalize-space()='' or normalize-space()='PARTICULAR_VALUE_HERE')
     ]"/>

Upvotes: 1

Related Questions