Creating xml with MarkupBuilder

This example will show how to create an xml document in a compact way using groovy's MarkupBuilder. If you attempted to create an xml document in java you have cried out loud. The MarkupBuilder is good for building simple xml while more advanced XML creation use StreamingMarkupBuilder to add namespaces, escape text or processing instructions. In the snippets below books will be used to define a simple xml structure, show how to add attributes and how to exclude empty or null attributes.

Create simple xml

@Test
public void create_simple_xml() {

    def writer = new StringWriter()
    def xml = new groovy.xml.MarkupBuilder(writer).books {
        book() {
            author("Kent Beck")
            title("Test Driven Development: By Example")
            price("37.99")
            description("Quite simply, test-driven development is meant to eliminate fear in application development.")
        }
    }

    println writer.toString()
}

Output

<books>
  <book>
    <author>Kent Beck</author>
    <title>Test Driven Development: By Example</title>
    <price>37.99</price>
    <description>Quite simply, test-driven development is meant to eliminate fear in application development.</description>
  </book>
</books>

Create xml with attributes

@Test
public void create_xml_with_attribute () {

    def writer = new StringWriter()
    def xml = new groovy.xml.MarkupBuilder(writer).books {
        book("id": 101) {
            author("Robert C. Martin")
            title("Clean Code: A Handbook of Agile Software Craftsm.")
            price("38.43")
            description("Even bad code can function.")
        }
    }

    println writer.toString()
}

Output

<books>
  <book id='101'>
    <author>Robert C. Martin</author>
    <title>Clean Code: A Handbook of Agile Software Craftsm.</title>
    <price>38.43</price>
    <description>Even bad code can function.</description>
  </book>
</books>

Omit empty or null attributes

@Test
public void create_xml_with_omit_attribute () {

    def writer = new StringWriter()
    def xml = new groovy.xml.MarkupBuilder(writer).books {
        setOmitEmptyAttributes(true)
        setOmitNullAttributes(true)
        book("id": "", "isbn": null) {
            author("Kishori Sharan")
            title("Beginning Java 8 APIs")
            price("free")
            description("Beginning Java 8 APIs, Extensions and Libraries...")
        }
    }

    println writer.toString()
}

Output

<books>
  <book>
    <author>Kishori Sharan</author>
    <title>Beginning Java 8 APIs</title>
    <price>free</price>
    <description>Beginning Java 8 APIs, Extensions and Libraries...</description>
  </book>
</books>