JavaRanch Home    
 
This page:         last edited 16 September 2007         What's Changed?         Edit

How To Pretty Print Xml With Java   

Here's an example using the XMLSerializer class from Xerces:


import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;
import org.w3c.dom.Document;
import java.io.OutputStream;

public class MyXmlPrettyPrinter {

    public void serialize(Document doc, OutputStream out) throws Exception {
        OutputFormat format = new OutputFormat(doc);
        format.setLineWidth(65);
        format.setIndenting(true);
        format.setIndent(2);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(doc);
    }
}

Here's an example using the JavaDoc:javax.xml.transformer.Transformer :


import java.io.OutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

public class MyXmlPrettyPrinter2 {

    public void serialize(Document doc, OutputStream out) throws Exception {
        
        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer serializer;
        try {
            serializer = tfactory.newTransformer();
            //Setup indenting to "pretty print"
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount""2");
            
            serializer.transform(new DOMSource(doc), new StreamResult(out));
        } catch (TransformerException e) {
            // this is fatal, just dump the stack and throw a runtime exception
            e.printStackTrace();
            
            throw new RuntimeException(e);
        }
    }
}



XmlFaq CategoryCodeSamples

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton