简短的谷歌搜索看起来你应该使用“MarkupBuilder”,但我不明白。看起来我可以“做XML”而已经完成了import grails.converters.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”解决,但比尔有更好的语法建议。
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
答案 0 :(得分:3)
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.thingie() {
someValue('blah')
hellaItems(){
item(){
anotherValue('yaddayadda')
}
item(){
anotherValue('different from the first')
}
}
}
writer.toString()
你得到了什么?语法有点奇怪,但那是因为它是DSL。它不应该看起来像普通的常规“代码”。 as XML
的工作方式完全不同,除非您的对象图与您准确发布的XML相匹配,否则您将无法获得所需的结果。
答案 1 :(得分:0)
基本上,如果您需要对生成的XML进行细粒度控制,请使用MarkupBuilder
。如果要以默认方式将对象(图形)序列化为XML,即所有属性都包含在标记中,则可以随意使用someObject as XML