在XmlSlurper的GPath中使用变量

Kee*_*gan 7 xml groovy

有没有办法让XmlSlurper通过变量获得任意元素?例如,我可以做一些像输入文件:

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

def xml = new XmlSlurper().parse(inputFile)
String foo = "record"
return xml.{foo}.size()
Run Code Online (Sandbox Code Playgroud)

我试过使用{}和$ {}和()如何转义这样的变量?或者没有办法?是否可以使用闭包的结果作为参数?所以我可以做点什么

String foo = file.record
int numRecords = xml.{foo.find(/.\w+$/)}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ner 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()
Run Code Online (Sandbox Code Playgroud)


Mic*_*ter 6

这个答案提供了一个代码示例,并且很大程度上归功于John 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 }
}
Run Code Online (Sandbox Code Playgroud)