【发布时间】:2011-07-13 21:52:04
【问题描述】:
简单的谷歌搜索看起来你应该使用“MarkupBuilder”,但我不明白。看起来我可以在完成 import grails.converters.XML 之后“作为 XML”执行,但这并没有真正给我想要的。
我想要这个:
<Thingie>
<someValue>blah</someValue>
<hellaItems>
<Item>
<anotherValue>yaddayadda</anotherValue>
</Item>
<Item>
<anotherValue>different from the first</anotherValue>
</Item>
</hellaItems>
</Thingie>
我什至不知道从哪里开始......
@Stefan 如果我想动态地做呢?我不认为我理解“建设者”一般可能是问题所在。
def items = ["yaddayadda","different from the first"]
更新:看起来我正在接近,但有人可以帮助我完成最后一部分。我正在这样做:
def items = ["yaddayadda","different from the first"]
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.thingie() {
someValue('blah')
hellaItems(){
items.each{
item(){
anotherValue(it)
}
}
}
}
def xmlString = writer.toString()
println "maybe this will just work"
println xmlString
打印:
maybe this will just work
<thingie>
<someValue>blah</someValue>
<hellaItems>
<item>
<anotherValue />
</item>
<item>
<anotherValue />
</item>
</hellaItems>
</thingie>
为什么我的anotherValue 不在那里?
更新:使用下面的“tmpHolder”解决,但 Bill 有更好的语法建议。
def items = ["yaddayadda","different from the first"]
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.thingie() {
someValue('blah')
hellaItems(){
items.each{
def tmpHolder = it
item(){
anotherValue(tmpHolder)
}
}
}
}
def xmlString = writer.toString()
println "maybe this will just work"
println xmlString
【问题讨论】:
-
你很接近,但我不会使用“它”,特别是如果你里面有另一个闭包。试试 items.each { txt -> item() { anotherValue(txt)} }?
-
是的,这比 tmpHolder 好很多。我还在学习 Groove。