Commenting XML content using Java

SAX parser can be used to add new comments or comment current content from an xml. JDOM gives an element called comment that can be used to create and write comments to a file. The below sample program details the way to comment out content from XML file.

Sample XML:

<?xml version="1.0" encoding="UTF-8"?>
<bookbank>
	<book type="fiction" available="yes">
		<name>Book1</name>
		<author>Author1</author>
		<price>Rs.100</price>
	</book>
	<book type="novel" available="no">
		<name>Book2</name>
		<author>Author2</author>
		<price>Rs.200</price>
	</book>
	<book type="biography" available="yes">
		<name>Book3</name>
		<author>Author3</author>
		<price>Rs.300</price>
	</book>
</bookbank>

Sample Program:


package blog.sample.code;

import java.io.FileWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

public class XMLCommentTest {

   public XMLCommentTest() throws Exception{
      String outputFile = "C:\\blog\\sample.xml";
      SAXBuilder builder = new SAXBuilder();
      Document document = builder.build(outputFile);
      Element root = document.getRootElement();
      List list = root.getChildren("book");
      List newList = new ArrayList();
      Iterator itr = list.iterator();
      while(itr.hasNext()){
      Element ele = itr.next();
         if(ele.getAttributeValue("type").equalsIgnoreCase("biography")){
            java.io.StringWriter sw = new StringWriter();
            XMLOutputter xmlOutput = new XMLOutputter();
            xmlOutput.output(ele, sw);
            Comment comment = new Comment(sw.toString());
            itr.remove();
            newList.add(comment);
         }
      }
      for(Comment com : newList){
         root.addContent(com);
      }
      document.setRootElement(root);
      XMLOutputter xmlOutput = new XMLOutputter();
      //xmlOutput.output(document, System.out);
      xmlOutput.output(document, new FileWriter(outputFile));
   }

   public static void main(String[] args) {
      try {
         new XMLCommentTest();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

}

The output of the above program is the updated sample.xml with the below content:

<?xml version="1.0" encoding="UTF-8"?>
<bookbank>
	<book type="fiction" available="yes">
		<name>Book1</name>
		<author>Author1</author>
		<price>Rs.100</price>
	</book>
	<book type="novel" available="no">
		<name>Book2</name>
		<author>Author2</author>
		<price>Rs.200</price>
	</book>
	<!-- <book type="biography" available="yes">
		<name>Book3</name>
		<author>Author3</author>
		<price>Rs.300</price>
	</book> -->
</bookbank>

==

Leave a comment