3

子要素が内部に別の子を持つことができるxmlでツリー構造を構築する必要があります。ネストされたノードの数は指定されていません。だから私はStreamingMarkupBuilderを使用しています:

def rootNode = ....


def xml = builder.bind { 

  "root"(type:"tree", version:"1.0") {
       type(rootNode.type)
       label(rootNode.label)

   "child-components" {
      rootUse.components.each { comp ->
                             addChildComponent(comp,xml)
            }
           }

  }

しかし、適切なaddChildComponentメソッドの作成に問題があります。何か案は ?

編集:わかりました私はそうしました:

def addChildComponent {comp,xml -> 
xml.zzz(){
    "lala"()
    }
}

しかし今、私は名前空間に問題があります:

<child-components>
<xml:zzz>
  <lala/>
</xml:zzz>
<xml:zzz>
  <lala/>
</xml:zzz>
<xml:zzz>
  <lala/>
</xml:zzz>
</child-components>

どうも

4

1 に答える 1

6

この場合、クロージャーaddChildComponentはまだ間違っています。"xml" (2 番目の) パラメーターをクロージャーに渡す代わりに、デリゲートを "親" クロージャーに設定する必要があります。

例:

def components = ['component1', 'component2', 'component3', 'componentN']
def xmlBuilder = new StreamingMarkupBuilder();

//this is "outside" closure
def addComponent = { idx, text ->
    //this call is delegated to whatever we set: addComponent.delegate = xxxxxx
    component(order:idx, text)
}

def xmlString = xmlBuilder.bind{
    "root"(type:'tree', version:'1.0'){
        type('type')
        label('label')
        "child-components"{
            components.eachWithIndex{ obj, idx->
                //and delegate is set here
                addComponent.delegate = delegate
                addComponent(idx, obj)
            }
        }
    }
}.toString()

println XmlUtil.serialize(xmlString)

出力:

<?xml version="1.0" encoding="UTF-8"?>
<root type="tree" version="1.0">
  <type>type</type>
  <label>label</label>
  <child-components>
    <component order="0">component1</component>
    <component order="1">component2</component>
    <component order="2">component3</component>
    <component order="3">componentN</component>
  </child-components>
</root>

これがお役に立てば幸いです。

于 2012-06-07T16:13:08.443 に答える