2012-08-08 2 views
4

xml 구조에서 노드를 더 깊이 추가하는 데 어려움이 있습니다. 나는 node와 nodeList 사이에 뭔가를 놓치고있다. 어떤 도움이라도 대단히 감사하겠습니다.그루비 노드와 노드 목록

def xml='''<Root id="example" version="1" archived="false"> 
<Item name="one" value="test"/> 
<Item name="two" value="test2"/> 
<Item name="three" value="test3"/> 
<AppSettings Name="foo" Id="foo1"> 
    <roles>foo</roles> 
</AppSettings> 
<AppSettings Name="bar" Id="bar1"> 
    <Item name="blue" value=""/> 
    <Item name="green" value=""/> 
    <Item name="yellow" value=""/> 
    <Roles> 
     <Role id="A"/> 
     <Role id="B"/> 
     <Role id="C"/> 
    </Roles> 
</AppSettings> 
</Root>''' 

root = new XmlParser().parseText(xml) 
def appSettings = root.'AppSettings'.find{[email protected] == "bar"}.'Roles' 
appSettings.appendNode('Role', [id: 'D']) 


def writer = new StringWriter() 
def printer = new XmlNodePrinter(new PrintWriter(writer)) 
printer.preserveWhitespace = true 
printer.print(root) 
String result = writer.toString() 

println result 

오류

groovy.lang.MissingMethodException: No signature of method: groovy.util.NodeList.appendNode() is applicable for argument types: (java.lang.String, java.util.LinkedHashMap) values: [Role, [id:D]] 

답변

8

여기이 선 :이 목록의 내용에 appendNode를 호출 할 수 있도록

def appSettings = root.'AppSettings'.find{[email protected] == "bar"}.'Roles' 

, 당신에게 NodeList를 (단일 노드를 포함)을 반환 목록 자체가 아닙니다.

이가 중 수행 할 수 있습니다 : 목록의 모든 요소에 appendNode를 호출합니다 어느

appSettings*.appendNode('Role', [id: 'D']) 

, 또는 순위 :

appSettings[0]?.appendNode('Role', [id: 'D']) 

어떤 목록의 첫 번째 요소에 appendNode를 호출합니다 (널 안전 연산자 ? 덕분에 첫 번째 요소가있는 경우).

+0

굉장! 감사합니다. Tim 저는 제가 누락 된 단순한 것이 있다는 것을 알고있었습니다. 조사하는 동안 아무 것도 찾을 수 없기 때문에 여러 번 투표 할 수 있기를 바랍니다. 다시 한번 감사드립니다. – zuichuan

관련 문제