简短的谷歌搜索看起来您应该使用“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

最佳答案

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完全匹配,否则您将无法获得所需的结果。

关于xml - 用grails制作XML的好方法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6686144/

10-11 22:14
查看更多