XMLBuilder : Easily build XML documents in Java
Dec 14th, 2008 by James Murty
I have long been irked by the difficulty of creating simple XML documents in Java code. While Java has excellent support for handling XML in general, if you just need to whip up a quick document — say, to interact with a web service API — you can quickly get lost in a messy quagmire of JAXP code that is difficult to write, to debug, and to stomach.
In the past, I have often resorted to building small XML documents using string concatenation to avoid this headache. And I’ve felt ashamed every time. Well, no more!
The XMLBuilder project I have just made available via Google Code contains a single utility class that makes it simple to create XML documents using relatively sparse Java code.
To create this XML document:
<?xml version="1.0" encoding="UTF-8"?>
<Projects>
<java-xmlbuilder language="Java" scm="SVN">
<Location type="URL">
http://code.google.com/p/java-xmlbuilder/
</Location>
</java-xmlbuilder>
<JetS3t language="Java" scm="CVS">
<Location type="URL">
http://jets3t.s3.amazonaws.com/index.html
</Location>
</JetS3t>
</Projects>
You would use the following code, which is nicely terse and closely resembles the structure of the XML document it produces:
XMLBuilder builder = XMLBuilder.create("Projects")
.e("java-xmlbuilder")
.a("language", "Java")
.a("scm","SVN")
.e("Location")
.a("type", "URL")
.t("http://code.google.com/p/java-xmlbuilder/")
.up()
.up()
.e("JetS3t")
.a("language", "Java")
.a("scm","CVS")
.e("Location")
.a("type", "URL")
.t("http://jets3t.s3.amazonaws.com/index.html");
If you’re interested, head on over the the Google Code project and download a copy. Feedback is welcome.
Hi james,
i currently use your XMLBuilder and i think it’s a great enhancement for writing XMLs.
After building my XML structure i put it into a file (like this builder.toWriter(writer, outputProperties);).
In thisnew xml-file everything is written in one line. Is there any possibility to insert automatically the correct line breaks?
Have you tried setting the following value for the output properties?
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, “yes”);
In my experience this setting will not always be effective at adding nice indentation to your XML output, but it should at least insert the correct line breaks.
Hi James,
thx for ur help. It actually worked with this setting.
If you want to have right indentation you have to set the outputProperties addtionally to his:
“outputProperties.put(“{http://xml.apache.org/xslt}indent-amount”, “2″)”
Perhaps you could add this to the google code page.
Greetz, detond