DOM

Create DOM document from scratch

This is an example of how to create a DOM Document from Scratch. We have implemented a method, that is void prettyPrint(Document xml), in order to convert a DOM into a formatted XML String. Creating a DOM Document from Scratch implies that you should:

  • Create an new Document, using newDocument() API method of DocumentBuilder.
  • Create the root element node of the Document, using createElement(String tagName) API method of Document, with the given tagname set to "root" and append it in the Document with appendChild(Node newChild) API method of Document.
  • Create a comment node, with a specified comment, with createComment(String data) API method of Document and insert it before the root element created above, using insertBefore(newChild, refChild) API method of Document.
  • Create a new element, and add it after the first child of the root element, using appendChild(Node newChild) API method.
  • In order to add an attribute to a Node, use setAttribute(String name, String value) API method of Element, with a specified attribute name and value.
  • Create a text Node, using createTextNode(String data) API method of Document and add it before the last Child of a specified Element, with insertBefore(Node newChild, Node refChild) API method of Document and using as refChild the last child of a specified element, with getLastChild() API method of Element.
  • Call void prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding. The method uses a Transformer, that is created using newTransformer() API method of TransformerFactory. The Transformer is used to transform a source tree into a result tree. After setting specific output properties to the transformer, using setOutputProperty(String name, String value) API method of Transformer, the method uses it to make the transformation, with transform(Source xmlSource, Result outputTarget) API method of Transformer. The parameters are the DOMSource with the DOM node and the result that is a StreamResult created from a StringWriter.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CreateDOMDocumentFromScratch {
	
	public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document doc = builder.newDocument();
		
		// create the root element node
		Element element = doc.createElement("root");
		doc.appendChild(element);

		// create a comment node given the specified string
		Comment comment = doc.createComment("This is a comment");
		doc.insertBefore(comment, element);

		// add element after the first child of the root element
		Element itemElement = doc.createElement("item");
		element.appendChild(itemElement);
		
		// add an attribute to the node
		itemElement.setAttribute("myattr", "attrvalue");
		
		// create text for the node
		itemElement.insertBefore(doc.createTextNode("text"), itemElement.getLastChild());
		
		prettyPrint(doc);
		
	}
	
	public static final void prettyPrint(Document xml) throws Exception {
		Transformer tf = TransformerFactory.newInstance().newTransformer();
		tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		tf.setOutputProperty(OutputKeys.INDENT, "yes");
		Writer out = new StringWriter();
		tf.transform(new DOMSource(xml), new StreamResult(out));
		System.out.println(out.toString());
	}

}

Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--This is a comment-->
<root>
<item myattr="attrvalue">text</item>
</root>

 
This was an example of how to create a DOM Document from Scratch in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button