Monday, August 13, 2007

Generating XML from Java using ECS is Simple and Easy

A tip on using the simple Jakarta Element Construction Set to output xml with.

Today, I had the need to produce some simple xml, from a simple object structure in Java. I was not in the mood to get one of the big guns into position (XStream, Xerces, DOM, JAXB, ...), but simply wanted to output some tag content easily, without importing the world in dependencies.

And then I found ECS, Jakarta Element Construction Set, which was just what I needed. It is simple to work with, and have a bare minimum of dependencies (as in none, nada, zip, nil, ingen, just the ecs jar).

The API of ECS is built like a fluent interface, so you can do code like this:
XMLDocument root = new XMLDocument(1.0, true, "UTF-8").addElement(new XML("books"))
.addElement(
new XML("book", true)
.addXMLAttribute("title", "Pragmatic Programmers")
.addXMLAttribute("rating", "Good").addElement(new XML("review", true).addElement("Blah blah")))
.addElement(
new XML("book", true)
.addXMLAttribute("title", "Programming in Foo")
.addXMLAttribute("rating", "Bad").addElement(new XML("review", true).addElement("Blah blah")));

String xmlString = root.toString("UTF-8");

Which produces this xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book title="Pragmatic Programmer" rating="Good">
<review>Blah blah</review>
</book>
<book title="Programming in Foo" rating="Bad">
<review>Blah blah</review>
</book>
</books>

The ECS project seems dead in that the mailing lists are inactive and that it is not actively maintained. Also, the documentation is lacking, even the Javadoc. Anyhow, it is a very simple API, and it did what I needed and worked well.

No comments: