2012-06-04 4 views
3

자식 요소가 다른 자식을 가질 수있는 xml 트리 구조를 작성해야합니다. 중첩 노드의 수가 지정되지 않았습니다. 그래서 StreamingMarkupBuilder를 사용하고 있습니다 :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> 

들으에게

답변

6

귀하의 폐쇄 addChildComponent이 여전히 잘못 케이스. "xml"(두 번째) 매개 변수를 닫음에 전달한 경우 대리자를 "부모"닫음으로 설정해야합니다.

예 :

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> 

당신이 도움이 바랍니다.

+0

네 도움이됩니다. 하지만 지금 내 바보 같은 문제는 내 노드가 use (yours 구성 요소 대신)라고해야하고 어떤 이유로 여기에서 예외가 발생한다는 것입니다 ("use"또는 "use"라고도 함). – wonglik

+1

http :// /stackoverflow.com/questions/11099292/creating-use-tag-with-streamingmarkupbuilder/11099470#11099470 – Tomo

관련 문제