XML 使用 Groovy 标记构建器语法编组 Grails 中的嵌套元素

XML marshalling of nested elements in Grails using Groovy markup builder syntax

Grails: v2.5.0

如何生成 XML 包含没有属性的嵌套元素?

这是我想要的输出:

<?xml version="1.0" encoding="UTF-8"?>
<list>
  <book>
    <title>Title</title>
    <authors>
      <author>
        <fname>First Name</fname>
        <lname>Last Name</lname>
      </author>
    </authors>
  </book>
</list>

使用以下编组器...

// imports...

class BootStrap {

  def init = { servletContext ->
    XML.registerObjectMarshaller(Book) { Book book, converter ->
      converter.build {
        title book.title
        authors {
          for (a in book.authors) {
            author {
              fname a.fname
              lname a.lname
            }
          }
        }
      }
    }
  }
}

...authors 元素未包含在输出中:

<?xml version="1.0" encoding="UTF-8"?>
<list>
  <book>
    <title>Title</title>
  </book>
</list>

但是,当向 authorsauthor 元素添加属性时...

// imports...

class BootStrap {

  def init = { servletContext ->
    XML.registerObjectMarshaller(Book) { Book book, converter ->
      converter.build {
        title book.title
        authors(bla: 'bla') {
          for (a in book.authors) {
            author(bla: 'bla') {
              fname a.fname
              lname a.lname
            }
          }
        }
      }
    }
  }
}

...元素包含在输出中:

<?xml version="1.0" encoding="UTF-8"?>
<list>
  <book>
    <title>Title</title>
    <authors bla="bla">
      <author bla="bla">
        <fname>First Name</fname>
        <lname>Last Name</lname>
      </author>
    </authors>
  </book>
</list>

有人能指出我正确的方向吗?

谢谢!

像这样给作者和作者调用添加空括号:

    converter.build {
      title book.title
      authors() {
        for (a in book.authors) {
          author() {
            fname a.fname
            lname a.lname
        }
      }
    }

this SO question with an example

找到解决方案:添加括号和一个空列表。

代码如下:

// imports...

class BootStrap {

  def init = { servletContext ->
    XML.registerObjectMarshaller(Book) { Book book, converter ->
      converter.build {
        title book.title
        authors([]) {
          for (a in book.authors) {
            author([]) {
              fname a.fname
              lname a.lname
            }
          }
        }
      }
    }
  }
}