Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for empty XML element using XSLT

Tags:

xml

xslt

I have the following XML

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
<Number1>
</Number1>
<Number2>11</Number2>
<Number3>12</Number3>
</ns0:Root>

In this case I am getting ENTER or \r\n for Number1. I want to write some XSLT to check if a node contains ENTER or \r\n and then replace it <Number1 />.

Can anyone help me to write the XSLT for this?

like image 984
ABC Avatar asked Jan 28 '26 18:01

ABC


1 Answers

There are different possible definitions of what an "empty element" could mean.

Let's define an empty element as one that doesn't have any element nodes children and whose string value is the empty string, or consists only of white space characters (' ', CR, NL).

Then to check if a given element is empty, use:

not(*) and not(normalize-space())

This assumes that the element is the context node when the XPath expression is evaluated.

In this case I am getting "ENTER" or "\r\n" for Number1. I want to write XSLT to check if node contain "ENTER" or "\r\n" then replace it .

You haven't specified with what this text node should be replaced, so in this solution I am assuming the text node should be replaced with the empty string (deleted):

<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 not(normalize-space())]">
  <xsl:element name="{name()}" namespace="{namespace-uri()}"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document:

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
    <Number1>
    </Number1>
    <Number2>11</Number2>
    <Number3>12</Number3>
</ns0:Root>

the wanted result is produced:

<ns0:Root xmlns:ns0="http://Map_Sample.Input_Schema">
   <Number1/>
   <Number2>11</Number2>
   <Number3>12</Number3>
</ns0:Root>
like image 191
Dimitre Novatchev Avatar answered Jan 30 '26 14:01

Dimitre Novatchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!