2009-08-20 2 views
7

XmlSlurper에 변수를 통해 임의의 요소를 가져올 수있는 방법이 있습니까? 예 : 내가 {}와 같은 $ {}과() 어떻게 탈출 할 변수를 사용하여 시도했다XmlSlurper의 GPath에서 변수 사용

<file> 
    <record name="some record" /> 
    <record name="some other record" /> 
</file> 

def xml = new XmlSlurper().parse(inputFile) 
String foo = "record" 
return xml.{foo}.size() 

: 그래서 입력 파일과 같은 일을 할 수 있습니까? 아니면 방법이 없습니까? 클로저의 결과를 인수로 사용할 수도 있습니까? 그래서

String foo = file.record 
int numRecords = xml.{foo.find(/.\w+$/)} 

답변

8
import groovy.xml.* 

def xmltxt = """<file> 
    <record name="some record" /> 
    <record name="some other record" /> 
</file>""" 

def xml = new XmlSlurper().parseText(xmltxt) 
String foo = "record" 
return xml."${foo}".size() 
+0

이 요소 루트 아닌 바로 아이들을 위해 작동하지 않습니다

이것이 고려하십시오. 관찰 : 데프 XML = 새 데프 xmltxt = "" " <레코드 이름 ="일부 기록 "/> <레코드 이름 ="다른 기록 "/> 을" "" XmlSlurper(). parseText (xmltxt) 문자열 foo = "something.record" 반환 값 xml "$ {foo}"크기() 다른 제안 사항이 있습니까? – Keegan

+0

나는 좋은 방법을 모른다. def aNode = xml foo.split ("\\."). each { aNode = aNode. "$ {it}" } return aNode.size() –

+0

그래, 최대 문자열 작동, 감사합니다 :) – Keegan

6

이 답변이 코드 예제를 제공하고, 그의 대답 존 W의 의견에 많은 빚을지고 같은 것을 할 수 있습니다.

import groovy.util.* 

def xml = """<root> 
    <element1>foo</element1> 
    <element2>bar</element2> 
    <items> 
    <item> 
     <name>a</name> 
     <desc>b</desc> 
    </item> 
    <item> 
     <name>c</name> 
     <desc>x</desc> 
    </item> 
    </items> 
</root>""" 

def getNodes = { doc, path -> 
    def nodes = doc 
    path.split("\\.").each { nodes = nodes."${it}" } 
    return nodes 
} 

def resource = new XmlSlurper().parseText(xml) 
def xpaths = ['/root/element1','/root/items/item/name'] 

xpaths.each { xpath -> 
    def trimXPath = xpath.replace("/root/", "").replace("/",".") 
    println "xpath = ${trimXPath}" 
    getNodes(resource, trimXPath).each { println it } 
} 
+0

여러분, 값을 어떻게 지정 하시겠습니까? 내 말은 : 당신의 [심지어 @Keegan 및 @ John.W] 권고가 작동하지 않는 "String foo ="something.record " xml."$ {foo} "= 값 ', 어떤 단서입니까? – Jrr

+0

여러분, 해결책을 찾았고,'def node = getNodes (..) node.replaceBody value'를 사용했습니다. 저는 XMLSlurper에서 연수생입니다. – Jrr