How to create XML programmatically in java / How to create XML using DOM parser in java / How to create XML file from java program

XML stands for eXtended Markup Language and is a widely used standard for transmitting information across systems mainly due to the flexibility it provides in creating the structure and data it can contain. That is, application developers can create their own structure which suits their application as there are no pre-defined tags in XML.

Scenario

Since it is a widely used standard, there arises a vital requirement to create an XML document either in the form of a String or a physical file from java application. Practical scenario is

when data of one component of your application data is stored in a database table and you want to make it available to some other application or for some other component of your application which is separate from this component and you cannot share the database details with either of them. The solution is you create an XML out of table data and share it with any component.

Create XML from Java Program using DOM Parser

Given below is a sample XML structure which we will be creating from java program. The structure is simple but enough for learning purpose and you can create more complex structure if you know how things work.

<?xml version=”1.0″ encoding=”UTF-8″?>
<Users>
<User id=”2″>
<name>codippa</name>
<User id=”2″>
</User>

The XML has a root tag with name Users and has child tags for each user details. A user tag is named as User which has user name in a child tag. Each user tag also has an id attribute.

Code to create above XML is given below followed by a detailed explanation of the same.

        import javax.xml.parsers.DocumentBuilder;
        import javax.xml.parsers.DocumentBuilderFactory;
        import javax.xml.parsers.ParserConfigurationException;
        import javax.xml.transform.OutputKeys;
        import javax.xml.transform.Result;
        import javax.xml.transform.Source;
        import javax.xml.transform.Transformer;
        import javax.xml.transform.TransformerConfigurationException;
        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.Document;
        import org.w3c.dom.Element;

  	public static void main(String[] args) throws ParserConfigurationException,
			TransformerException {
		DocumentBuilder builder = null;
		try {
			builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw e;
		}
		Document document = builder.newDocument();
		// create root element
		Element root = document.createElement("Users");
                // attach it to the document
		document.appendChild(root);
                // create user node
		Element user = document.createElement("User");
                // create its id attribute
		user.setAttribute("id", "2");
                // add user node to root node
		root.appendChild(user);
                // create name node and set its value
		Element userName = document.createElement("name");
		userName.setTextContent("codippa");
                // attach this node to user node
		user.appendChild(userName);
                // write xml
		Transformer transformer;
		try {
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			transformer = transformerFactory.newTransformer();
			Result output = new StreamResult(new File("codippa.xml"));
			Source input = new DOMSource(document);
                        // if you want xml to be properly formatted
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.transform(input, output);
		} catch (TransformerConfigurationException e) {
			throw e;
		} catch (TransformerException e) {
			throw e;
		}
	}
Details :
At first step, create a org.w3c.Documentobject. This object is a handle to the XML file. Next we need to create individual nodes as required by the XML structure. In every XML, the first node is the root node which contains all other nodes. Hence, we first create a root node.

A node is created using createElement() method of org.w3c.Document. Method of creating a node is the same, whether it is a root node or a child node. The only difference what makes a node as root or child is the node to which we attach the newly created node.
For Example, we get a node using createElement()method. Let’s name it as node1. Now if we attach it to the document object, then it becomes the root node. If we attach it to another node, say node2, then node1 becomes the child of node2.

For creating an attribute of a node (such as id attribute in ), call setAtrribute() method on a node. This method takes two arguments, attribute name and its value.

A node is attached using appendChild() method. For creating multiple nodes inside a node, such as <name>, <country> nodes inside <User> node, create three nodes, one of User and the other two of name and country. Attach name and country nodes to the User node (using appendChild()method off course) and attach User node to the root node.
In this way multiple nodes can be created and attached to the root or to another node (for creating child nodes).

Let’s tweak in :

  1. Besides using setAttribute() method directly on a node, an attribute can also be created using below code
          // create an attribute with given name
          Attr attr = document.createAttribute("id");
          // set its value
          attr.setValue("1");
          // attach it to desired node
          user.setAttributeNode(attr);
    
  2. org.w3c.dom package is included in jdk itself so there is no need to add any other library to classpath when using it.
  3. org.w3c.dom.Document is an interface which represents the entire XML document. It contains methods for creating various components of an XML document such as nodes, comments, attributes.
  4. org.w3c.Node is an interface which represents a node in XML and contains methods for fetching nodes and for node manipulations (such as for inserting a node before another, removing a node etc.).
  5. org.w3c.dom.Document is the child interface of org.w3c.dom.Node and hence has methods for node creation as well as their manipulations.
  6. A javax.xml.parsers.ParserConfigurationException may be thrown while creating a document builder, hence it needs to be handled.
  7. A javax.xml.transform.Transformeris used to convert XML Document to a physical file.
  8. A Transformer may throw a javax.xml.transform.TransformerExceptionin case there is an error while converting a document to a file.
  9. For printing the generated XML to the console instead of writing it to a file, probably for debugging, just make the below change :
     // this will write to a file
     Result output = new StreamResult(new File("codippa.xml"));
     // this will print to console
     Result output = new StreamResult(System.out);
    

Did this post help you solve a problem? Wonderful !!!! Keep visiting for more solutions…

Leave a Reply