Constructing XML content
The previous Reading XML using XmlSlurper, Reading XML using XmlParser, and Searching in XML with GPath recipes have been useful to learn the ingredients and the techniques for consuming and querying XML documents. In this recipe, we will cover how to produce XML using Groovy's MarkupBuilder
.
How to do it...
Let's create a bibliography XML similar to the one we used in the Reading XML using XmlSlurper recipe.
In order to start using
MarkupBuilder
, you first need to import it since it's not available by default:import groovy.xml.MarkupBuilder
Then you need to create a writer object that will be responsible for the final output of the XML content. For the sake of simplicity let's use:
java.io.StringWriter: def writer = new StringWriter()
Finally, we need to create an instance of
MarkupBuilder
and pass the writer object to it:def xml = new MarkupBuilder(writer)
At this point, we are ready to create some XML:
xml.bibliography { author('William Shakespeare') play { year...