How to create XML in java using DOM parser ? Create & indent of XML with Java code.

This tutorial covers about how to create a XML file using DOM Parser in Java and also covers that how to indent an XML using java . XML is made up of Elements . You can visit my earlier tutorial for more on XML and How to traverse / parse an XML. DOM allows a developer to create objects like root, child elements , comments and text nodes, etc. Document interface have the factory methods to create these objects. Elements are represented by Element interface , can have other elements , text, attributes . Document and Element interface inherit Node interface which is the primary datatype for the DOM.

Some of the methods of Document & Element interface to create XML are as follows .
1. createElement(String tagName) : creates an element using the tagname in the document.
2. createComment(String data) : to create comment node of the given string
3. createTextNode(String data) : to create a Text node of the given string.
4. setAttribute(java.lang.String name, java.lang.String value) : method of Element that adds a new attribute to the element.
5. appendChild(Node newChild) : method of Element inherited from Node which is used to add the child element node

The following is the sample e-mail in XML format .

 <?xml version="1.0" encoding="utf-8" standalone="no"?>
 <!--Sample XML format of Email -->
 <subject>Message from TechLabs</subject>
    <receipient role="to">
 <bodytext>Hope this URL will help you to learn about how to create XML using DOM.</a></bodytext>

Steps to create an XML using DOM . There are no fixed steps to create XML. I have used the following steps to create the above Email XML.
1. Create a Document to put DOM tree
2. Create the root element of the document . Add attribute and comments of root element if required
3. Create child element of the root element, and add attribute and comments of child
4. Add text node to the child elements
5. Create a Transformer to transform a source tree from the memory into a result which may be DOMResult , SAXResult or StreamResult. StreamResult is constructed from a file , string writer , outputstream , etc..

To indent of an XML , the following statements are used using the transformer object.

transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{}indent-amount", "3");


Java 5 transformer may not give the expected result with the indenting request due to bugs in Java 5.

You will get the clear idea when you create the above Email XML with the following code.

import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;

public class CreateDomXml {
    public static void main (String args[]) {

    public static void createDomXml() {
        try {
//to create document to put DOM tree.
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();

//to create root element email
            Element root = doc.createElement("email");

//to create comment
            Comment comment = doc.createComment("Sample XML format of Email ");

            Element subject = doc.createElement("subject");

            Text subText = doc.createTextNode("Message from JavaOnline");

//to create child element from and text node of that element
            Element from = doc.createElement("from");
            Text fromText = doc.createTextNode("");

            Element fromdisplay = doc.createElement("fromdisplay");
           Text fromdisplayText = doc.createTextNode("JavaOnline");

            Element receipients = doc.createElement("receipients");

          Element receipient = doc.createElement("receipient");
           receipient.setAttribute("role", "to"); // to create attribute with value

           Element email_id = doc.createElement("email-id");
            Text emailidText= doc.createTextNode("");

           Element disp = doc.createElement("display");
            Text dispText= doc.createTextNode("VKJ");

           Element bodytext = doc.createElement("bodytext");
           Text bodytextText = doc.createTextNode("Hope this URL will help you to learn about  how to create XML using DOM.");

          Element  sign= doc.createElement("signature");
           Text signText = doc.createTextNode("Administrator");

//to create transformer
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  

//to include the  xml declaration line  <?xml version="1.0" encoding="utf-8" standalone="no"?>
             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

//for indent of XML
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             transformer.setOutputProperty("{}indent-amount", "3");

// to write into a file
          // String fileName= "D://as2/jf6/email1.xml";
          //  StreamResult result = new StreamResult(new File(fileName));

            DOMSource source = new DOMSource(doc);

//to write as  a string
           StringWriter sw = new StringWriter();
           StreamResult result = new StreamResult(sw);
            transformer.transform(source, result);
            //System.out.println("XML file saved " + fileName);

           String xmlString = sw.toString();
            System.out.println("Email XML \n\n " + xmlString);

        } catch (Exception e) {

xml creation

You may also like

Leave a Reply

Be the First to Comment!