Java HTML / XML How to - Create a DOM Document from root element tag name








Question

We would like to know how to create a DOM Document from root element tag name.

Answer

/*from w w w .  j  av  a  2  s  . co  m*/
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
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.Element;

public class Main {

  public static void main(String[] argv) throws Exception {
    Document doc = createXmlDocument("root");

    System.out.println(documentToString(doc));

  }

  /**
   * Start a new XML Document.
   * @param rootName The name of the Document root Element (created here)
   * @return the Document
   * @throws DomException
   */
  public static Document createXmlDocument(String rootName) throws Exception {
    DocumentBuilderFactory factory;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);

    Document  document  = factory.newDocumentBuilder().newDocument();
    Element   root      = document.createElement(rootName);

    document.appendChild(root);
    return document;
  }

  
  public static String documentToString(Document document) {
    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer trans = tf.newTransformer();
      StringWriter sw = new StringWriter();
      trans.transform(new DOMSource(document), new StreamResult(sw));
      return sw.toString();
    } catch (TransformerException tEx) {
      tEx.printStackTrace();
    }
    return null;
  }
}

The code above generates the following result.