Validate empty XML element with 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 get ENTER

or \r\n

for Number1

. I want to write XSLT to check if a node contains ENTER

or \r\n

and then replace it <Number1 />

.

Can anyone help me write XSLT for this?

+3


source to share


2 answers


There are various possible definitions of what an empty element means .

Let's define an empty element as one that has no element node children, and whose string value is an empty string or consists of only space characters ('', CR, NL).

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

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

      

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

In this case, I get "ENTER" or "\ r \ n" for Number1. i want to write XSLT to check if node contains "ENTER" or "\ r \ n" then replace it.



You did not specify that this node text should be replaced, so in this solution I am assuming that the node text should be replaced with an empty string (removed):

<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 to the provided XML document:

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

      

the desired result is obtained :

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

      

+10


source


Try the following:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[normalize-space(string(.)) = '']"/>
</xsl:stylesheet>

      



Explanation: Skip the output for elements where the text content (full descendant) is pure white space.

0


source







All Articles