简体   繁体   中英

Groovy MarkupBuilder

I have a list of things, each of which might be a foo or a bar. I want to build some xml that looks like this:

<rdf:RDF>
  <foo id="1">
  <foo id="2">
  <bar id="3">
</rdf:RDF>

So I have gotten this far:

MarkupBuilder xml = new MarkupBuilder(writer)
  xml.'rdf:RDF' (nsmap) { }

But now I am stuck. How do i - within that xml.'rdf:RDF' (nsmap) { } closure - iterate over my list of stuff? How do i - within that iterator - spit out a foo or a bar element as applicable?

Its simpler as you may think. Include a loop in the xml closure and in turn include markup in the loop. This script ...

import groovy.xml.MarkupBuilder

things = ['foo','foo','bar']
writer = new StringWriter()

xml = new MarkupBuilder(writer)
xml.'rdf:RDF' {
    things.eachWithIndex {thing,index ->
        "$thing" id:index+1
    }
}

println writer

... will produce following output:

<rdf:RDF>
  <foo id='1' />
  <foo id='2' />
  <bar id='3' />
</rdf:RDF>

Here You go:

import groovy.xml.MarkupBuilder
import org.custommonkey.xmlunit.*

def data = [foo:1,bar:2,baz:3]

def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.'rdf:RDF' {
    data.each { e ->
        "$e.key"(id:e.value)
    }
}
println writer

Ok.

The issue is that when a closure is run by a builder, it operates within the context of the builder. Now, it turns out that the builder context hides methods, but does not hide variables. This means that you can create a closure, assign it to a variable, and access it from within the builder.

NOw, I get the impression that this closure, too, runs in the context of the builder. But I suspect you can assign "this" to a variable outside the closures and then access that variable to get the context back.

It's ridiculous that you have to go to this sort of trouble. Im reminded of coding in Microsoft Access, back in the 90's. It works great, until the moment when you want to do something more than it was strictly designed to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM