Grails Cookbook - A collection of tutorials and examples

Groovy Create XML Document Examples

In previous examples, we show how to parse XML documents using XmlSlurper and XmlParser. This post will show the opposite. We give examples on how to create XML documents.

Simple Example To Create XML

Below is a simple example on how to construct information and store it's XML representation to a String variable:

package test
import groovy.xml.MarkupBuilder
/**
 * A Simple Example that builds an XML document.
 */
class Test {
    static main(args) {
        def stringWriter = new StringWriter()
        def peopleBuilder = new MarkupBuilder(stringWriter)
        peopleBuilder.people {
            person {
                firstName('John')
                lastName('Doe')
                age(25)
            }
            person {
                firstName('Jane')
                lastName('Smith')
                age(31)
            }
        }
        def xml = stringWriter.toString()
        println xml
    }
}

The code is very simple as shown above. We just need to instantioate a MarkupBuilder and create the information using it. The MarkupBuilder accepts a writer object in the constructor, and we pass a StringWriter to it. The final XML is stored in the xml variable. Below is the expected output of the code:
<people>
  <person>
    <firstName>John</firstName>
    <lastName>Doe</lastName>
    <age>25</age>
  </person>
  <person>
    <firstName>Jane</firstName>
    <lastName>Smith</lastName>
    <age>31</age>
  </person>
</people>

Create XML And Save To File

Since MarkupBuilder accepts any objects that extends a Writer, we can pass a FileWriter to it to output the result to a file. Below is a simple example to show that. It is a minor tweak to the code shown above:
package test
import groovy.xml.MarkupBuilder
/**
 * A Simple Example that builds an XML document and saves the result to a file.
 */
class Test {
    static main(args) {
        def fileWriter = new FileWriter("c:/temp/testdb.xml")
        def peopleBuilder = new MarkupBuilder(fileWriter)
        peopleBuilder.people {
            person {
                firstName('John')
                lastName('Doe')
                age(25)
            }
            person {
                firstName('Jane')
                lastName('Smith')
                age(31)
            }
        }
        fileWriter.close();
    }
}
And the result is saved to "c:/temp/testdb.xml"
Posts about XML