Oct 13

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


<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

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

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

</xsl:stylesheet>

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: , ,


6 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:

    Hi,

    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

Leave a Reply