What is an alternative to this XPath //div[@id='foo']
in GPath? In general, where I can find this documentation?
Asked
Active
Viewed 2.4k times
4 Answers
30
Here is the corresponding snippet:
def node = new XmlSlurper().parseText(...)
def foo = node.depthFirst().findAll { it.name() == 'div' && it.@id == 'foo'}
A few other links you may want to read:

BugOrFeature
- 327
- 1
- 6
- 13

Nicolas Modrzyk
- 13,961
- 2
- 36
- 40
-
4It's Groovy, not GPath. I need a single GPath expression. – yegor256 Aug 11 '11 at 04:59
-
3Not too sure what you mean, since GPath is mostly using groovy syntax with the following extra symbols: ".." that returns the parent "*" that returns all the children "**" that act as a depth first loop "@" that is used to access a property the normal node accessor. – Nicolas Modrzyk Aug 11 '11 at 05:13
9
The previous poster gave you all that's required: Assuming your document has been slurped into xml
, you want
def foo = xml.path.to.div.find{it.@id == 'foo'}
to find a single result. Or findAll
to find all results.

winstaan74
- 1,131
- 7
- 11
-
-
1ok. then the previous poster gave you the solution: - use `xml.depthFirst().find{it.name() == 'div' && id.@id == 'foo}` – winstaan74 Aug 12 '11 at 10:00
-
@winstaan74 What's the expression for getting all elements with a specific attribute name? – raffian Jun 01 '14 at 02:03
-
2
3
To mimic the expression //div[@id='foo'] the closest thing you can do with a GPath is:
def xml = new XmlParser().parseText(text)
xml.'**'.div.findAll { it.@id=="foo" }
the '**' is pretty much the same as '//' in your XPath.
xml.'**'.div
will yield all the nodes of type div at any level.
Later filtering with findAll() with the given closure you get a list of nodes as you do in the XPath case

user1708042
- 1,740
- 17
- 20
1
what you need is this:
def root = new XmlSlurper().parseText(<locOfXmlFileYouAreParsing>.toURL().text)
def foundNode = root.'**'.find{ it.@id == "foo" }
its the double * that will let you find it without knowing the path. At least this is how I do it.
-
1How do you find the first instance of a node by element name, assuming there's more than one? – raffian Oct 11 '12 at 02:21
-
`xml.'**'.find { it.name() == 'elementName' }` And that will be the first one. – AbuNassar Jul 06 '16 at 13:58