2012-03-14 4 views
1

XMLSlurper를 사용하고 있습니다. 내 코드는 아래에 있지만 작동하지 않습니다. 문제는 "id"속성이없는 노드에 도달하면 실패한다는 것입니다. 어떻게해야합니까?groovy에서 특정 속성 값을 갖는 노드의 텍스트를 어떻게 찾을 수 있습니까?

//Parse XML 
def page = new XmlSlurper(false,false).parseText(xml) 

//Now save the value of the proper node to a property (this fails) 
properties[ "finalValue" ] = page.find { 
    it.attributes().find { it.key.equalsIgnoreCase('id') }.value == "myNode" 
}; 

"id"속성이없는 노드 만 고려하면 실패하지 않습니다. 어떻게해야합니까?

답변

0

Apprently 나는 단순히 depthFirst를 사용할 때 작동하도록 할 수 있습니다. 따라서 :

properties[ "finalValue" ] = page.depthFirst().find { 
    it.attributes().find { it.key.equalsIgnoreCase('id') }.value == "myNode" 
}; 
1

GPath 표기법을 사용하고 "@id"가 먼저 비어 있는지 확인하십시오.

다음 코드 단편은 id 애트리뷰트가 "B"이고 값이 "bizz"이므로 "bizz"와 "B"를 출력합니다.

def xml = new XmlSlurper().parseText("<foo><bar>bizz</bar><bar id='A'>bazz</bar><bar id='B'>bizz</bar></foo>") 
def x = xml.children().find{[email protected]() && it.text()=="bizz"} 
println x 
println [email protected]