How to find element by attribute value in GPath?

22,626

Solution 1

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:

Solution 2

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.

Solution 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

Solution 4

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.

Share:
22,626
yegor256
Author by

yegor256

Lab director at Huawei, co-founder at Zerocracy, blogger at yegor256.com, author of Elegant Objects book; architect of Zold.

Updated on December 11, 2020

Comments

  • yegor256
    yegor256 over 3 years

    What is an alternative to this XPath //div[@id='foo'] in GPath? In general, where I can find this documentation?

  • yegor256
    yegor256 almost 13 years
    It's Groovy, not GPath. I need a single GPath expression.
  • Nicolas Modrzyk
    Nicolas Modrzyk almost 13 years
    Not 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.
  • yegor256
    yegor256 almost 13 years
    // in XPath means that I don't know the exact path to div
  • winstaan74
    winstaan74 almost 13 years
    ok. then the previous poster gave you the solution: - use xml.depthFirst().find{it.name() == 'div' && id.@id == 'foo}
  • raffian
    raffian over 11 years
    How do you find the first instance of a node by element name, assuming there's more than one?
  • raffian
    raffian almost 10 years
    @winstaan74 What's the expression for getting all elements with a specific attribute name?
  • AbuNassar
    AbuNassar almost 8 years
    xml.'**'.findAll { it.@attributeName }
  • AbuNassar
    AbuNassar almost 8 years
    xml.'**'.find { it.name() == 'elementName' } And that will be the first one.