Search code examples
xsltxslt-2.0

Remove whitespace left by element removal using XSLT


I am using an XSLT empty template to remove a node from my XML. that is, <xsl:template match="note"/>. It works fine but I am left with an empty line between the nodes either side of it. I want to retain whitespace in general and have indented output but just get rid of this blank line. Is there a way to do that or would I have to run through teh document a second time and match somehow on the blank line?

...
<name>Keep whitespace</name>
                                       <-- where the <note/> element was
<favourite-color>keep white space</favourite-color>
...

Ideally I'd have:

...
<name>Keep whitespace</name>
<favourite-color>keep white space</favourite-color>
...

Solution

  • In many cases it can suffice to strip white space when parsing and to indent the output when serializing: <xsl:strip-space elements="*"/><xsl:output indent="yes"/>.

    Or you can use <xsl:template match="note | text()[not(normalize-space()) and preceding-sibling::node()[1][self::note]]"/>.