DOM

Add comment to DOM document

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

  • Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
  • Set the parser produced so as not to validate documents as they are parsed, using setValidating(boolean validating) API method of DocumentBuilderFactory, with validating set to false.
  • Create a new instance of a DocumentBuilder, using newDocumentBuilder() API method of DocumentBuilderFactory.
  • Parse the FileInputStream with the content to be parsed, using parse(InputStream is) API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOM Document object.
  • Get the Document Element using getDocumentElement() API method of Document.
  • Create a new Comment, using createComment(String data) API method of Document.
  • Get the parent node of the Document Element, and use insertBefore(Node newChild, Node refChild) API method of Node, for the parent node, to insert the comment before the specified child of the parent node.
  • 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.File;
import java.io.FileInputStream;
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 AddCommentToDOMDocument {
	
public static void main(String[] args) throws Exception {
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setValidating(false);
		DocumentBuilder db = dbf.newDocumentBuilder();
		
		Document doc = db.parse(new FileInputStream(new File("in.xml")));
		
		Element element = doc.getDocumentElement();
		Comment comment = doc.createComment("This is a comment");
		element.getParentNode().insertBefore(comment, element);
		
		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());
	}

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples</title>
		<item>
			<title><![CDATA[Java Tutorials]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

Output:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--This is a comment-->
<rss version="2.0">
	<channel>
		<title>Java Tutorials and Examples</title>
		<item>
			<title><![CDATA[Java Tutorials]]></title>
			<link>http://www.javacodegeeks.com/</link>
		</item>
	</channel>
</rss>

  
This was an example of how to add comments to a DOM Document in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron 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.

8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Giselle aga
7 years ago

Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

Alisha Ross
5 years ago

Great tremendous things here. I’m very glad to look your article. Thank you so much and i am taking a look ahead to contact you. Will you please drop me a mail?

surbhi nahta
5 years ago

Great information, I get so much information from post and replies. I request you to please write some informative post on java Training.

Aayushi Verma
4 years ago

Thanks for sharing that blog. I want to know more about the best builders in Bhopal. Because I am planning to start my own construction on a large scale.

surbhi nahta
4 years ago

I am really happy to found such a helpful and fascinating post that is written in well manner. Thanks for sharing such an informative post.

Vigneshwar
3 years ago

I enjoyed your post because I found that you have some good basic points that most everyone can benefit from. 

Natasha Romanoff
2 years ago

Thanks for sharing this amazing info

MV RAHUL
1 year ago

Thank you for sharing this. Your personal experience adds authenticity to the topic, and I can relate to what you’ve shared.
Angular Training In Hyderabad

Back to top button