views:

369

answers:

2

I'm doing some XML processing with groovy. Specifically, I'm inhaling an XML file via XMLParser, doing a whole batch of in-memory processing, and then serializing the resulting data back out to XML via a MarkupBuiler.

The vast majority of the data in the file gets transferred to a non-xml based object hierarchy to talk to the gui and have processing done, so the two XML files never know about each other.

However, there is one slug of XML that lives at the edge of the source file that needs to get copied verbatim to the output XML file with little or no processing. Is there a way I can hand the MarkupBuilder a nodelist from XMLParser and have it just insert that into the document?

Something like this:

def builder = new MarkupBuilder()
builder.outermosttag( name: 'library') {
  someothertag( name: 'shelf' ) {

    //magically insert a nodelist of arbitrary XML from somewhere else

  }
}
A: 

I haven't actually tried this... but if you serialize the nodelist to a string you might be able to do this:

builder.yieldUnescaped(xmlString)

still kinda messy though...

danb
+1  A: 

XmlParser returns a Node and I don't know of any way to insert it into a Markup or StreamingMarkupBuilder without converting to a xml string.

import groovy.xml.*

def x = """
<root>
  <somenode1>
      <anode>foo</anode>
  </somenode1>
  <somenode2>
      <anode>bar</anode>
  </somenode2>
</root>
""".trim()
def otherXml = new XmlParser().parseText(x)

def writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(otherXml.somenode1[0])

def builder = new MarkupBuilder()
builder.outermosttag( name: 'library') {
  someothertag( name: 'shelf' ) {

    mkp.yieldUnescaped writer.toString() //magically insert a nodelist of arbitrary XML from somewhere else

  }
}

For this kind of work I tend to use XmlSlurper along with the StreamingMarkupBuilder:

import groovy.xml.*

def x = """
<root>
  <somenode1>
      <anode>foo</anode>
  </somenode1>
  <somenode2>
      <anode>bar</anode>
  </somenode2>
</root>
""".trim()
def otherXml = new XmlSlurper().parseText(x)

def builder = new StreamingMarkupBuilder().bind {
    outermosttag( name: 'library') {
        someothertag( name: 'shelf' ) {

            mkp.yield otherXml.somenode1 //magically insert a nodelist of arbitrary XML from somewhere else

        }
    }
}
John Wagenleitner