I’ve always loved Groovy builders concept for handling (mostly creating) hierarchical documents. On the other hand I find StAX, pull-based processing API, to be one of my favorite methods for dealing with simple XML processing. It’s simple and fast, so what more can I ask for? Additionally, thanks to the Jettison project you can also use the StAX API to handle JSON documents. So, basically we can use one simple (standard) API to handle both XML and JSON documents in the same manner. The next logical step is to merge these two great pieces of technology into one.
Meet the StaxBuilder, a Groovy builder that uses StAX API to create documents. You can currently find it here, but I hope it will find a more appropriate place soon (Groovy code base, for example).
Anyway, here are a few examples that demonstrate how to build XML and JSON documents using this builder (taken from test cases).
Creating XML using Woodstox
WstxOutputFactory factory = new WstxOutputFactory()
StringWriter writer = new StringWriter()
StaxBuilder builder = new StaxBuilder(
factory.createXMLStreamWriter(writer)
)
builder.root1(a:5, b:7) {
elem1('hello1')
elem2('hello2')
elem3(x:7)
}
assert writer,
"""<root1 a="5" b="7">
<elem1>hello1</elem1>
<elem2>hello2</elem2>
<elem3 x="7" />
</root1>"""
Creating JSON using Jettison
MappedNamespaceConvention con = new MappedNamespaceConvention();
StringWriter writer = new StringWriter()
MappedXMLStreamWriter mappedWriter
= new MappedXMLStreamWriter(con, writer);
StaxBuilder builder = new StaxBuilder(mappedWriter)
builder.root1(a:5, b:7) {
elem1('hello1')
elem2('hello2')
elem3(x:7)
}
assert writer,
"""{"root1":{"@a":"5","@b":"7",
"elem1":"hello1",
"elem2":"hello2",
"elem3":{"@x":"7"}
}}"""