Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Closure based Creation of XML



Groovy provides a very powerful and idomatic ways to build XML using closures with the help of MarkupBuilder. It provides a declarative approach to create an XML using closures.

Creating a basic XML document

Using MarkupBuilder we can easily create the XML document as shown below −

Example.groovy

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def xmlMovies = new MarkupBuilder(writer)

xmlMovies.movies {
   movie(title: 'Transformers') {
      type('Anime, Science Fiction')
      format('DVD')
      year(1989)
      rating('R')
      stars('R')
      description(8)
   }
}

def generatedXml = writer.toString()
println generatedXml

Output

When we run the above program, we will get the following result.

<movies>
   <movie>
      <type>War, Thriller</type>
      <format>DVD</format>
      <year>2003</year>
      <rating>PG</rating>
      <stars>PG</stars>
      <description>10</description>
   </movie>
</movies>

Adding attributes

we can add attributes as named parameter in a closure.

Example.groovy

import groovy.xml.MarkupBuilder

def writer = new StringWriter()
def markupBuilder = new MarkupBuilder(writer)

markupBuilder.employee(name: 'Alice', age: 30) {
   department('Admin')
}

def generatedXml = writer.toString()
println generatedXml

Output

When we run the above program, we will get the following result.

<employee name='Alice' age='30'>
  <department>Admin</department>
</employee>

Collect data from Lists and create multiple elements

Example.groovy

import groovy.xml.MarkupBuilder

def items = [
    [name: 'Laptop', price: 12000],
    [name: 'Mouse', price: 250],
    [name: 'Keyboard', price: 750]
]

writer = new StringWriter()
builder = new MarkupBuilder(writer)

builder.items {
    items.each { product ->
        item {
            name(product.name)
            price(product.price)
        }
    }
}

println writer.toString()

Output

When we run the above program, we will get the following result.

<items>
  <item>
    <name>Laptop</name>
    <price>12000</price>
  </item>
  <item>
    <name>Mouse</name>
    <price>250</price>
  </item>
  <item>
    <name>Keyboard</name>
    <price>750</price>
  </item>
</items>

Advantages of Closure based XML Creation

  • Improved Readability − Closure based code resembles closely with XML structure makes it easy to read and understand.

  • Conciseness −Closure based approach without any boilerplate code is very concise and clear.

  • Integrated − Groovy control flow and data structures works well with closures which makes XML creation easy..

  • Expressive − MarkupBuilder employes DSL, Domain Specific Language which makes XML creation looks natural.

Advertisements