Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

XSL transform to remove elements *and* clear remaining whitespace

843834Apr 20 2009
Some time ago I tried to determine how to remove the blank lines that were present in an xml document after running said xml document through a transform to remove elements. When transforming a document to "delete" an element and retain the rest of it, the whitespace node preceding the deleted node will appear as a blank line in the output. This may or may not pose a problem depending on what you plan to do with the document after it's transformed -- for me it was problem. So since I've never seen anyone post a solution to this problem I thought I'd share mine.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:output method="xml" indent="no" encoding="utf-8"/>

  <!-- copy nothing when matching on the elements that are to be deleted -->
  <xsl:template match="FOO"/>
  <xsl:template match="BAR"/>

  <!-- remove the newline text nodes that preceded the elements being deleted -->
  <xsl:template match="text()">
    <xsl:if test="name(following-sibling::*) != 'FOO' and name(following-sibling::*) != 'BAR'">
      <xsl:copy>
        <xsl:value-of select="."/>
      </xsl:copy>
    </xsl:if>
  </xsl:template>

  <!-- recursively handle the entire document -->
  <xsl:template match="@*|*">
    <xsl:copy>
      <xsl:copy-of select="namespace::*"/>
      <xsl:apply-templates select="@*|*|text()"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>
If starting with the following document:
<TEST>
  <FOO>blah</FOO>
  <BAR>blah</BAR>
</TEST>
and running a transform to delete <FOO> and <BAR> without clearing the whitespace you'll end up with the following:
<TEST>


</TEST>
whereas if you use the entire transform I've shown above you'll end up with the following:
<TEST>
</TEST>
Now this is a very contrived example but you get the picture. Hope this helps someone else, too.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 18 2009
Added on Apr 20 2009
0 comments
476 views