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.

  1. In order to start using MarkupBuilder, you first need to import it since it's not available by default:
    import groovy.xml.MarkupBuilder
  2. 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() ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.