Java tutorial
//package com.java2s; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main { /** * Create new XML document. * * @param rootElementName name of the root element to add, or <code>null</code> if the * document should not have any root just yet * @throws ParserConfigurationException */ public static Document createEmptyDocument(String rootElementName) throws ParserConfigurationException { return createEmptyDocument(rootElementName, null); } /** * Create new XML document. * * @param rootElementName name of the root element to add, or <code>null</code> if the * document should not have any root just yet * @throws ParserConfigurationException */ public static Document createEmptyDocument(String rootElementName, String namespace) throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); Document result = builder.newDocument(); if (rootElementName != null) { Element rootElement; if (namespace != null && !namespace.isEmpty()) { rootElement = result.createElementNS(rootElementName, namespace); } else { rootElement = result.createElement(rootElementName); } result.appendChild(rootElement); } return result; } }