Showing posts with label XML with Java. Show all posts
Showing posts with label XML with Java. Show all posts

How to create XML in java using DOM parser | XML with Java


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>TechLabs</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 TechLabs");
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("TechLabs");
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);
}
}
}