Groovy嵌套(递归?)XML

时间:2017-01-21 00:47:44

标签: groovy

给定一个包含ID和ELEMENT的对象列表,我需要迭代列表并生成如下所示的XML:

<object id="1">
    <element>...</element>
    <object id="2">
        <element>...</element>
        <object id="3">
            <element>...</element>
            </object>
        </object>
    </object>

注意每个对象都是在上一个对象中创建的,对象仅在列表末尾关闭。 (不是我的选择,由外部接口决定)

有没有办法使用XML标记生成器生成它?

1 个答案:

答案 0 :(得分:3)

class MyElement {
  def id
  def element
}

def list = [new MyElement(id: 1, element: "element1"),
            new MyElement(id: 2, element: "element2"),
            new MyElement(id: 3, element: "element3")]

println new groovy.xml.StreamingMarkupBuilder().bind {
  def foo // note declaration and initialization on different lines
  foo = { List<MyElement> l ->
    if (l.isEmpty()) return
    def head = l.head()
    def tail = l.tail()
    object {
      id head.id
      element head.element
      foo(tail)
    }
  }
  foo(list)
}

输出(美化):

<object>
  <id>1</id>
  <element>element1</element>
  <object>
    <id>2</id>
    <element>element2</element>
    <object>
      <id>3</id>
      <element>element3</element>
    </object>
  </object>
</object>`