It is possible to Create an XML file in Java with the DOM, however it is necessary to create the document with the DocumentBuilder class, and then create each element with the Element class. Finally you will use the Transformer class to generate a text file with the content of the XML.
package com.geekole; // Name of your java package import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; 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.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author geekole.com */ public class CreateXMLFile { public static void main(String argv[]) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); //Root element Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("root"); doc.appendChild(rootElement); //First element Element element1 = doc.createElement("element1"); rootElement.appendChild(element1); //An attribute is added to the element node and its value Attr attr = doc.createAttribute("id"); attr.setValue("attribute value"); element1.setAttributeNode(attr); Element element2 = doc.createElement("element2"); element2.setTextContent("Element 2 content"); rootElement.appendChild(element2); //Write the XML content to a file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("/path/test.xml")); transformer.transform(source, result); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } }
Although there are other ways to create an XML document, this is one of the most used. The result will be an XML file like the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <root> <element1 id="attribute value"/> <element2>Element 2 content</element2> </root>