Writing out a DOM tree to System.out

You can do this using the XSLT transform package. In XSLT, it is called an identity transform when the transformation is generating the source without any changes.

The following example programmatically creates a DOM tree and uses the Transformer class to output it to System.out.


import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
public class Main
   public static void main(String []args) {
      Document doc;
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.newDocument();
         Element customers = doc.createElement("customers");
         Element customer = doc.createElement("customer");
         Element name = doc.createElement("name");
         name.appendChild(doc.createTextNode("Joris Van den Bogaert"));
         // use the XSLT transformation package to output the DOM tree we just created
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transformer = tf.newTransformer();
         transformer.transform(new DOMSource(doc), new StreamResult(System.out));
      catch(Exception e) {


<?xml version="1.0" encoding="UTF-8"?>
<customers><customer><name>Joris Van den Bogaert</name></customer></customers>