Thursday, July 10, 2014

Using Groovy MarkupBuilder to generate XML Declaration and DOCTYPE

I found Groovy MarkupBuilder can also generate xml declaraion and doctype, with the help of groovy.xml.MarkupBuilderHelper class. Following is the example

def sw = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(sw)

def helper = new groovy.xml.MarkupBuilderHelper(xml)
helper.xmlDeclaration([version:'1.0', encoding:'UTF-8', standalone:'no'])
helper.yieldUnescaped """<!DOCTYPE note SYSTEM "note.dtd">
"""

xml.person{
  firstname("Steve")
  lastname("Zhang")
  country("Canada")
  city("Toronto")
}

println sw.toString()


And the result:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE note SYSTEM "note.dtd">
<person>
  <firstname>Steve</firstname>
  <lastname>Zhang</lastname>
  <country>Canada</country>
  <city>Toronto</city>
</person>