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>

1 comment:

  1. Thanks a lot Steve I was getting crazy with the syntax for the xmlDeclaration !
    Also still wondering how it work for the pi (process instruction).
    Syntax is not clear to me.
    so for now I’m using a the basic yieldUnescaped for this:
    helper.yieldUnescaped("\n")

    ReplyDelete