# StaxBuilder

version 2.4.21

A Groovy builder that works with Streaming API for XML (StAX) processors.

Here is a simple example using the StAX implementation of Java to generate XML:

    def factory = javax.xml.stream.XMLOutputFactory.newInstance()
    def writer = new StringWriter()
    def builder = new groovy.xml.StaxBuilder(factory.createXMLStreamWriter(writer))

    builder.root(attribute:1) {
        elem1('hello')
        elem2('world')
    }

    assert writer.toString() == '<?xml version="1.0" ?><root attribute="1"><elem1>hello</elem1><elem2>world</elem2></root>'

An external library such as Jettison can be used as follows:

    @Grab('org.codehaus.jettison:jettison:1.3.3')
    @GrabExclude('stax:stax-api') // part of Java 6 and later
    import org.codehaus.jettison.mapped.*

    def writer = new StringWriter()
    def mappedWriter = new MappedXMLStreamWriter(new MappedNamespaceConvention(), writer)
    def builder = new groovy.xml.StaxBuilder(mappedWriter)

    builder.root(attribute:1) {
         elem1('hello')
         elem2('world')
    }

    assert writer.toString() == '{"root":{"@attribute":"1","elem1":"hello","elem2":"world"}}'