Oct 13

Use an XSL transformation with the xsl:strip-space instruction.

<xsl:stylesheet version="1.0" 

<xsl:output method="xml" omit-xml-declaration="yes"/>

  <xsl:strip-space elements="*"/>

  <xsl:template match="@*|node()">
    <xsl:apply-templates select="@*|node()"/>


TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(
   new StreamSource("strip-space.xsl"));

DOMSource source = new DOMSource(document);          
StreamResult result = new StreamResult(System.out);  

transformer.transform(source, result); 

written by objects \\ tags: , ,

7 Responses to “How do I remove whitespace from an XML Document?”

  1. Dieter Says:

    Thanks a lot, saved my day 🙂

  2. objects Says:

    No worries 🙂

  3. Julien Says:

    great tip :-), works well with the Transformer trick for indenting

  4. anon Says:


    Thanks for the info. Saved a lot of my time. 🙂
    This works like a charm when used in conjuction with the “Reformat/Auto-format” functionality of Visual Studio.

  5. bala Says:

    Thanks lot

  6. objects Says:

    no worries

  7. Priya Says:

    When i open the DOM document string with Notepad , it shows some space before the tag. I used the code given above in my existing XSL . It did not work for me .

    From java though i did trim , after opening this with notepad, space is coming

Leave a Reply

You must be logged in to post a comment.