【问题标题】:Whats a good way to make XML with grails什么是用 grails 制作 XML 的好方法
【发布时间】: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。

标签: xml grails groovy


【解决方案1】:
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 完全匹配,否则您将无法获得您想要的结果。

【讨论】:

  • 在某处有 items.each{} 之前,我想我无法理解这个答案。
  • 显然我比我想象的要聪明。
  • 您不应该在这些元素的末尾使用方法调用 () 括号。
【解决方案2】:

基本上,如果您需要对生成的 XML 进行细粒度控制,请使用 MarkupBuilder。如果您想以默认方式将对象(图形)序列化为 XML,即所有属性都包含在标记中,请随意使用someObject as XML

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2010-10-16
    • 2014-05-03
    相关资源
    最近更新 更多