XPath / XSLT Remove Empty Tags

I would like to remove tags that contain only whitespace / newline / tab characters, as shown below:

<p> </p> 

How do you do this with the xpath and xslt template functions?

+7
source share
1 answer

This conversion (rule override):

 <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(text()[normalize-space()])]"/> </xsl:stylesheet> 

when applied to the following XML document :

 <t> <a> <b> <c/> </b> </a> <p></p> <p> </p> <p>Text</p> </t> 

correctly produces the desired result :

 <t> <a> <b/> </a> <p>Text</p> </t> 

Remember . Using and overriding an identity rule / template is the most fundamental and powerful XSLT design template. This is the right choice for many problems in which most nodes should be copied unchanged and only some specific nodes should be changed, deleted, renamed, ... etc.

Note : @Abel in his comment recommends that some fragments of this solution be further clarified:

For the uninitiated or curious: not(*) means: do not have a child element; not(text()[normalize-space()]) means: absence of node text with text that does not contain white space.

+10
source

All Articles