Create an XML document with DOM : XML Serialization « XML « Java Tutorial


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;

import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Document doc = impl.createDocument(null, null, null);
    Element e1 = doc.createElement("api");
    Element e2 = doc.createElement("java");

    e2.setAttribute("url", "");
    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

33.21.XML Serialization
33.21.1.Saving a DOM tree to XML file javax.xml.parsers (JAXP)
33.21.2.PropsToXML takes a standard Java properties file, and converts it into an XML file
33.21.3.Writing a DOM Document to an XML File
33.21.4.Writing Only the Text of a DOM Document
33.21.5.Create an XML document with DOM
33.21.6.Strip extra spaces in a XML string
33.21.7.Extracting an XML formatted string out of a DOM object