16

I had an xml of the following pattern

<?xml version="1.0" encoding="UTF-8"?>
    <Person>
      <FirstName>Ahmed</FirstName>
      <MiddleName/>
      <LastName>Aboulnaga</LastName>
      <CompanyInfo>
        <CompanyName>IPN Web</CompanyName>
        <Title/>
    <Role></Role>
        <Department>
    </Department>
      </CompanyInfo>
    </Person>

I used the following xslt (got from forums) in my attempt to remove empty tags

 <xsl:template match="@*|node()">
<xsl:if test=". != '' or ./@* != ''">
  <xsl:copy>
  <xsl:copy-of select = "@*"/>
    <xsl:apply-templates />
  </xsl:copy>
</xsl:if>

The xslt used is successful in removing tags like

<Title/>
    <Role></Role>

...but fails when empty tags are on two lines, eg:

<Department>
    </Department>

Is there any fix for this?

5
  • 2
    Good question, +1. See my answer for a complete, short and easy solution that doesn't use any conditional instructions or explicit priorities and is based on the most fundamental and powerful XSLT design pattern -- overriding the identity rule. Jul 11, 2011 at 12:53
  • 4
    Be careful with your terminology. Your department element is not empty, because whitespace is significant in XML elements. You can say that it contains only spaces, but you can't say that it's empty.
    – Wayne
    Jul 11, 2011 at 15:14
  • +1 for question and effort. See my answer to know about the XPath 1.0 function needed to achieve the wanted result and how to do that with just one single template. Jul 11, 2011 at 19:54
  • The provided solutions down there meet your requirements. I wonder why you haven't accepted/voted any of them. Jul 1, 2013 at 13:05
  • Just a note on terminology: Tags mark the start and end of elements. Tags can't be empty. You're looking to remove empty elements, not tags.
    – Roger Dahl
    Jul 1, 2019 at 17:35

6 Answers 6

18

This transformation doesn't need any conditional XSLT instructions at all and uses no explicit priorities:

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

When applied on the provided XML document:

<Person>
    <FirstName>Ahmed</FirstName>
    <MiddleName/>
    <LastName>Aboulnaga</LastName>
    <CompanyInfo>
        <CompanyName>IPN Web</CompanyName>
        <Title/>
        <Role></Role>
        <Department>
        </Department>
    </CompanyInfo>
</Person>

it produces the wanted, correct result:

<Person>
   <FirstName>Ahmed</FirstName>
   <LastName>Aboulnaga</LastName>
   <CompanyInfo>
      <CompanyName>IPN Web</CompanyName>
   </CompanyInfo>
</Person>
6
  • hey there :) I have a quick question. Incase if node <CompanyName> is blank too, then the output XML would have FirstName, Last Name and a null tag <CompanyInfo> that is because all of its child elements are null tags. That is fair enough for the requirement. But what what would be the effort incase if I want to get rid of the <CompanyInfo> since its child nodes are null, and inturn the parent of <CompanyInfo> too (if (assuming) <CompanyInfo> is only child of its parent and now the whole hierarchy is null). Thanks in advance. Jul 1, 2013 at 13:01
  • For convinience we can assume that the given XML is only part of original XML, And mandatory nodes like "ROW_ID" will always be populated. So OUTPUT XML won't be blank. I have come up with a code that can ignore a node which has no child element having data. But I'm facing some problem with the recursiveness, I mean the parent of a parent of null nodes and so on.. Jul 1, 2013 at 13:04
  • 1
    @InfantPro'Aravind', Just add CompanyName[not(node) or not(*//node())] to the match pattern of the last template. Jul 1, 2013 at 14:22
  • @dimitre-novatchev This works for the given scenario but what if I want to do this recursively as in , consider the following example -> ... <Rsn/> <aaa1> <bbb1> <sss/> </bbb1> </aaa1> .... After running the transformation , only the inner most tag is removed i.e. <sss/> ; and the outer <rsn> is removed ; but I want to remove the whole <aaa1> block Jun 27, 2017 at 10:16
  • 1
    @dimitre-novatchev Thanks for the quick reply , I have found the required solution here on SO Jun 27, 2017 at 15:39
4
<xsl:template match="@*|node()">
  <xsl:if test="normalize-space(.) != '' or ./@* != ''">
    <xsl:copy>
       <xsl:copy-of select = "@*"/>
       <xsl:apply-templates/>
    </xsl:copy>
  </xsl:if>
</xsl:template>
3
  • 1
    @Bob Vale: Why would you delete an element that has one or more attributes (even all of these have value '') ? Jul 11, 2011 at 12:56
  • @Bob Vale: Your code deletes an element like <x y="" z=""/> Jul 11, 2011 at 13:32
  • 1
    Oh, so you mean deletes an element with empty attributes. It's because I copied the code the questioner used and assumed they wanted that.
    – Bob Vale
    Jul 11, 2011 at 13:35
3

(..) Is there any fix for this?

The tag on two lines is not an empty tag. It is a tag containing spaces inside (like new lines and possibly some kind of white space characters). The XPath 1.0 function normalize-space() allows you to normalize the content of your tags by stripping unwanted new lines.

Once you have applied the function to the tag content you can then check for the empty string. A good way to do this is by applying the XPath 1.0 boolean() function to the tag content. If the content is a zero-length string its result will be false.

Finally you can embed everything slightly changing your identity transform. You do not need xsl:if instructions or any other additional template.

The final transform will look like this:

<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()[boolean(normalize-space())]
                         |@*"/>
     </xsl:copy>
 </xsl:template>

</xsl:stylesheet>

Additional note

Your xsl:if instruction is currently checking also for empty attributes. In that way you are actually removing also non-empy tags with empty attributes. It does not sound like just "Removing empty tags". So be careful, or you question is missing some detail, or you are using unsafe code.

1

Your question is underspecified. What does empty mean? Is <outer> empty here?

<outer><inner/></outer>

Anyway, here's one approach that might fit your bill:

<xsl:template match="*[not(.//@*) and not( normalize-space() )]" priority="3"/>

Note you might have to tweak the priority to fit your needs.

1

You can use the following xslt to remove empty tags/attributes:

<?xml version="1.0" encoding="UTF-8"?>
<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:template match="node()">
        <xsl:if test="normalize-space(string(.)) != ''
                        or count(@*[normalize-space(string(.)) != '']) > 0
                        or count(descendant::*[normalize-space(string(.)) != '']) > 0
                        or count(descendant::*/@*[normalize-space(string(.)) != '']) > 0">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
        </xsl:if>
    </xsl:template>

    <xsl:template match="@*">
        <xsl:if test="normalize-space(string(.)) != ''">
            <xsl:copy>
                <xsl:apply-templates select="@*" />
            </xsl:copy>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>
0

From what I have found on the net, this is the most correct answer:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
    <xsl:template match="/">
        <xsl:apply-templates select="*"/>
    </xsl:template>
    <xsl:template match="*">
            <xsl:if test=".!=''">
                <xsl:copy>
                  <xsl:copy-of select="@*"/>
                  <xsl:apply-templates/>
                </xsl:copy>
            </xsl:if>
    </xsl:template>
</xsl:stylesheet>
1
  • This creates empty lines where it removes empty tags, this doesn't work with newlines and this doesn't work with blank tags. May 24, 2023 at 9:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.