Output DOM tree with indent in Java

Description

The following code shows how to output DOM tree with indent.

Example


import java.io.OutputStream;
import java.io.StringReader;
/* www.  ja v  a2  s  .  c om*/
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class Main {
  
  public static void main(String[] argv) throws Exception {
    StringReader sr = new StringReader("<tag>java2s.com</tag>");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder loader = factory.newDocumentBuilder();

    Document document = loader.parse(new InputSource(sr));
    
    writeXml(document, System.out);

  }
  public static void writeXml(Node n, OutputStream os) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    // identity
    Transformer t = tf.newTransformer();
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.transform(new DOMSource(n), new StreamResult(os));
}
}

The code above generates the following result.





















Home »
  Java Tutorial »
    XML »




DOM
SAX