Akusete
Akusete

Reputation: 10794

Mixing Groovy MarkupBuilder with Converters

I am trying to inject XML fragments created by an XML converter into an MarkupBuilder.

However I cannot get the formatting correct, and it seems as though there is unnecessary intermediate serialisation steps.

import grails.converters.XML
import groovy.xml.MarkupBuilder

//...

def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
   status ("OK")
   myList.each { it as XML } //Insert objects by converting to XML
}
println writer.toString()

The output required would be

<response>
  <status>OK</status>
  <foo>
     <field>5</field>
  </foo>
  <foo>
     <field>5</field>
  </foo>
</response>

My current attempt is this

def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
   status ("OK")
   myList.each {
     xml.mkp.yieldUnescaped ( it as XML )
   }
}
println writer.toString()

However currently each xml fragment is preceeded by

  <?xml version="1.0" encoding="UTF-8"?>

Is there a groovier way to achieve this?

Upvotes: 1

Views: 1059

Answers (1)

rochb
rochb

Reputation: 2236

The groovier way would be to pass your writer directly to the render method of the XML class as shown below.

def writer = new StringWriter ()
def xml = new MarkupBuilder (writer)
xml.response {
   status ("OK")
   def xmlist = myList as XML
   xmlist.render(writer)
}      

You'll still have the encoding information one time though since render just writes it to any writer passed in.

I see 2 options to get rid of this encoding information:

  • get the string representation of the XML as you did, and take off the encoding information as shown below (can be improved)
  • write your own XML converter using Groovy MarkupBuilder as explained in this article.

 xml.response {
    status ("OK")
    def xmlist = myList as XML
    xml.mkp.yieldUnescaped (xmlist.toString() - "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;")
}

Upvotes: 2

Related Questions