First of all, saying that your input XML contains "empty elements with whitespaces in them" is very misleading. Elements that have whitespace characters as their content are not empty at all. Instead, they contain a text node as a child, that in turn contains only whitespace characters.
You can remove the whitespace content of otherwise empty elements with the XSLT element strip-space
.
This only affects whitespace-only text nodes of elements, for example
<li> </li>
On the other hand, strip-space
will not remove the whitespace in text nodes like
<li>dhd ddj d</li>
To also normalize the whitespace of text nodes that contain characters other than whitespace, use the normalize-space()
function:
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
normalize-space()
removes trailing whitespace and replaces any sequence of whitespace characters with a single whitespace.
Stylesheet (XSLT 1.0)
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:transform>
XML Input
<ul class="list">
<li> </li>
<li>Hello world!</li>
</ul>
XML Output
<ul class="list">
<li/>
<li>Hello world!</li>
</ul>
Another code example, that illustrates the use of normalize-space()
:
XML Input
<ul class="list">
<li> </li>
<li>Hello world! </li>
</ul>
Stylesheet
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="UTF-8" indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:transform>
XML Output
<ul class="list">
<li/>
<li>Hello world!</li>
</ul>