Tuesday, June 1, 2010

Simple XML Writer / Indenter

Recently, I was again looking for an easy way to generate a few lines of nicely formatted XML. I don't want to use a fat XML library and a serialization process for this simple task. Since I couldn't find a suitable solution so I wrote it myself.

For instance, with the following piece of code:
XmlWriter xml = new XmlWriter();
xml.beginElement("GeoData", "xmlns='http://geo.net/data'");
xml.beginElement("Cities");

xml.beginElement("Australia").print("Sydney").endElement();
xml.beginElement("Germany").printLine("Berlin").printLine("Munich").endElement();

xml.endElement();
xml.endElement();
System.out.println(xml.toString());
you get this:
<?xml version="1.0" encoding="UTF-8"?>


  
    Sydney
    
      Berlin
      Munich
    
  

Quite straightforward. Its like a simliar class we where using at work. Not having dependencies on big XML libraries also means you can use it in GWT applications where no such dependencies are allowed. I'm using this class for my GWT based travel blog.

You can download it here:
- XmlWriter.java
- XmlWriterTest.java

If its useful for you, write a comment.

No comments: