Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables in XmlSlurper's GPath

Tags:

xml

groovy

Is there a way to have XmlSlurper get arbitrary elements through a variable? e.g. so I can do something like input file:

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

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

I've tried using {} and ${} and () how do I escape variables like that? Or isn't there a way? and is it possible to use results from closures as the arguments as well? So I could do something like

String foo = file.record
int numRecords = xml.{foo.find(/.\w+$/)}
like image 954
Keegan Avatar asked Aug 20 '09 18:08

Keegan


2 Answers

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()
like image 186
John Wagenleitner Avatar answered Nov 04 '22 04:11

John Wagenleitner


This answer offers a code example, and owes a lot to John W's comment in his answer.

Consider this:

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 }
}
like image 34
Michael Easter Avatar answered Nov 04 '22 04:11

Michael Easter