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"?>
<email>
 <!--Sample XML format of Email -->
 <subject>Message from TechLabs</subject>
 <from>j2eeforum@rediffmail.com</from>
 <fromdisplay>JavaOnline</fromdisplay>
 <receipients>
    <receipient role="to">
    <email-id>vkj@xyz.com</email-id>
    <display>VKJ</display>
    </receipient>
 </receipients>
 <bodytext>Hope this URL will help you to learn about how to create XML using DOM.</a></bodytext>
 <signature>Administrator</signature>
</email> 

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("{http://xml.apache.org/xslt}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 java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

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

    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");
            doc.appendChild(root);

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

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

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

//to create child element from and text node of that element
            Element from = doc.createElement("from");
            root.appendChild(from);
            Text fromText = doc.createTextNode("j2eeforum@rediffmail.com");
            from.appendChild(fromText);

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

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

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

           Element email_id = doc.createElement("email-id");
            receipient.appendChild(email_id);
            Text emailidText= doc.createTextNode("vkj@xyz.com");
            email_id.appendChild(emailidText);

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

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

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

//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("{http://xml.apache.org/xslt}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) {
            System.out.println(e);
        }
    }
} 


Output:
xml creation

Leave a Reply

cbd medical the cbd project cbd additive cbd benefits research cbd topical cream for pain how to use sublingual cbd procanna cbd natures way cbd tennessee cbd oil cbd oil retailers where do i get cbd oil jb hi fi melbourne cbd opening hours allergic reaction to cbd oil rash cbd oil while getting a tattoo snopes cbd oil cbd oil doesnt work for me plus cbd oil logo is cbd oil legal in nevada solace cbd can you get high off of cbd charlottes web cbd oil story cbd oil and knee pain do they test for cbd cbd oil does it get you high cbd vaginal cream cbd hemp oil spray how to use cbd e liquid 1500mg cbd oil full spectrum cbd oil vs smoking hemp 500 milligrams cbd oil cbd oil production in hampden county ma will cbd cause positive drug test the complete guide to cbd oil does cbd oil promote bone growth

male potency drugs best penis volume pills phallocare male enhancement reviews penis enlargement ads sleeve tst 11 male enhancement reviews best boner pill king kangaroo male enhancement reviews chemical penis enlargement dht african back ant male enhancement gnc pills good for sexual health penis enlargement jelqing natural gain male enhancement reviews ron jermy penis enlargement reviews otc ed pills what are happy pills called best male enhancement devices generic ed pills whole foods immediate male enhancement pills anxiety medicines over the counter science behind penis pills reddit erection pills vitality rx male enhancement black ryno male enhancement does score male enhancement work male enhancement used by the rock enlargement creams amazon dietary supplements approval perminate gains penis pills best sex pills for longer sex penis enlargement pil ryno pills sex black rhino pills walmart dietary supplements market clinical tested premium male enhancement pill

quick weight loss center diet plan pdf veggie diet plan to lose weight rapid weight loss pill weight loss injections and pills arx weight loss pills grenade pills weight loss what are some safe weight loss pills what are the most good weight loss pills how to know its the original keto diet pills eating well 7 day weight loss diet meal plan lose weight keep muscle diet plan the doctors celebrity weight loss pills lose weight and gain muscle diet infinity weight loss pills side effects 1200 vegan diet to lose weight weight loss pills for 87 99 weight loss drug recall oriental quick weight loss diet weight loss pills make you stomach growl supplement and weight loss keto weight loss pills is it safe best high protein low carb diet for weight loss nv weight loss supplement with hoodia what are good weight loss pills pomelo diet weight loss bet weight loss pill the best weight loss diet for women hcg weight loss drops diet apple cider vinegar lose weight pills suzy bae weight loss diet how many apple cider vinegar pills to lose weight what pills do they take at wausau weight loss colon cleanse pills lose weight weight loss supplements for thyroid patients