Using MarkupBuilder in Grails

Posted By : Aakash Baweja | 03-Sep-2013

MarkupBuilder

Markupbuilder is a class in groovy that basically helps to create XML in a more readable format.

For this purpose we use groovy.xml.MarkupBuilder.

To test the functioning of MarkupBuilder, make an application and write the following code in the action of the Controller of the application:-


def index() {
  
  def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.records() {
  student(name:'Rahul Kumar', R.No.:'01', year_of_admission:2012) {
    country('India')
    course('B.Tech')
  }
  student(name:'Jack white', R.No.:'02', year_of_admission:2011) {
    country('U.S')
    course('Philosophy')
  }
  car(name:'Pierre', R.No.:'03', year_of_admission:2010) {
    country('France')
    course('Pharmacy')
  }
}

println writer.toString()
render "hello"
 }

This code will render the result in an XML form.

To create the same XML in Java, it would take 50-60 lines of code. But with the help of Groovy's MarkupBuilder, things became quite simple.

Groovy is able to accomplish this because it is a dynamic language.

Java , on the other hand, is static: Java compiler ensures that all methods exist before you can call them.

In the API docs for MarkupBuilder, we will find neither records() method nor student() method.

Groovy catches the calls to these methods that don't exist and generates well-formed XML.

Constructor of MarkupBuilder can take Writer, PrintWriter or IndentWriter as parameter.

If nothing is passed in parameter, then by default it writes the output to stdout as soon as it executes.

Markupbuilder can also be used to create HTML pages.

For example:



def fileWriter = new FileWriter('firstPage.html')

def markup = new groovy.xml.MarkupBuilder(fileWriter)

 

markup.html {

head {

title 'This is my First Page'

}

body {

p 'This is the first page of my HTML document'

}

}

Here, we are creating a basic HTML page which sets a title for the page and then has one paragraph section.

StreamingMarkupBuilder

MarkupBuilder is great for building simple XML documents synchronously.

For more-advanced XML creation, StreamingMarkupBuilder is used.

With it we can add all kinds of XML extras, such as processing instructions, namespaces, and unescaped text using the mkp helper object.

mkp is a special namespace used to escape away from the normal building mode of the builder and get access to helper markup methods 'yield', 'pi', 'comment', 'out', 'namespaces', 'xmlDeclaration' and 'yieldUnescaped'.

We can use getMkp() of MarkupBuilder to obtain the mkp object.

StreamingMarkupBuilder produce the final XML only when we call the bind() method, passing in the closure that contains the markup and all of the instructions.

This allows us to build up various parts of the XML document asynchronously and output them all at once.

Example:


def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def employee = builder.bind {
    mkp.xmlDeclaration()
    mkp.declareNamespace('myCompany':'http://myCompany/records/info')
    employee(count: 3) {
        emp(id: 1) {
            title  'Ajay Singh'
            mycompany.dept 'accounts'
        }
       emp(id: 2) {
            title  'Manish Kumar' 
            mycompany.dept 'Networking'
        }
       emp(id: 3) {
            title 'Rajat Arora'  
            mkp.comment('Yet to Join')            
        }
        emp(id: 4) {
            mkp.yieldUnescaped 'Ritu Khanna'
        }
    }
}

println XmlUtil.serialize(books)


Output:


  
    Ajay Singh
    accounts
  
  
    Manish Kumar
    Networking
  
  
    Rajat Arora
    
  
  
    Ritu Khanna
  


About Author

Author Image
Aakash Baweja

Request for Proposal

Name is required

Comment is required

Sending message..