简体   繁体   English

Groovy MarkupBuilder

[英]Groovy MarkupBuilder

I have a list of things, each of which might be a foo or a bar. 我有一个东西列表,每个东西都可能是foo或bar。 I want to build some xml that looks like this: 我想构建一些看起来像这样的xml:

<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? 我如何-在该xml.'rdf:RDF' (nsmap) { }闭包中-遍历我的工作清单? How do i - within that iterator - spit out a foo or a bar element as applicable? 我如何在该迭代器中吐出foo或bar元素(如适用)?

Its simpler as you may think. 您可能会认为它更简单。 Include a loop in the xml closure and in turn include markup in the loop. 在xml闭包中包含一个循环,然后在循环中包含标记。 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. 但我怀疑您可以将“ this”分配给闭包外部的变量,然后访问该变量以获取上下文。

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. 我想起了90年代Microsoft Access中的编码。 It works great, until the moment when you want to do something more than it was strictly designed to do. 效果很好,直到您想要做的事情比严格设计的要多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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