I had to build relatively simple XML strings from user input recently in a project and was trying to come up with a beautiful, elegant solution to do it. Naturally, manual string concatenation was out. It’s messy, brittle, and basically a nightmare to maintain. My next alternative was XMLBeans but I rejected as it was too heavyweight. I didn’t need to register a schema and it was simply too inefficient and a huge overkill to use XMLBeans to generate a straightforward XML string due to the amount of boilerplate required.
Another consideration was that I wanted to build the string in the style of fluent interfaces, such that one could simply tell if the string was well formed simply by eyeballing it. I thought of using VTD-XML, which was the XML parser being used in the project, but I couldn’t find any XML building capabilities, only parsing ones. I then settled on JDom as I’ve used it before as well as a new kid on the block, java-xmlbuilder (uses JAXP internally to build the DOM). With that, let’s see some code!
Element orderXml= new Element("ORDER").addContent(new Element
XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
StringWriter stringWriter = new StringWriter();
xmlOutputter.output(new Document(orderXml), stringWriter);
// JDom output
<?xml version="1.0" encoding="UTF-8"?>
XMLBuilder xmlBuilder =
Properties outputProperties = new Properties();
// java-xmlbuilder output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
Needless to say, I decided to use java-xmlbuilder as I found it more readable and also, it’s more easier to write code in the style of fluent interfaces with it. With JDom, I had to really pay attention to the indentation and bracketing as the correct visual position of the elements do not necessarily mean that your XML is well-formed. Get the order of your method calls and your closing brackets mixed up and even though it looks right, the resulting string will be malformed.
For java-xmlbuilder, coding in the style of fluent interfaces comes naturally due to the API and the brackets are simple to match up. The really cool thing about this is that once you have finished adding items to a new element, you can call the up() method to retrieve the XMLBuilder node that represents the parent of the current node. If you balance every call to element() with a call to up(), you can write code that closely resembles the structure of the XML document you are creating.