How to find element by attribute value in GPath?

假如想象 提交于 2019-12-05 09:57:48

问题


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


回答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:

  • GPath documentation
  • Processing XML with Groovy



回答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.




回答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




回答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.



来源:https://stackoverflow.com/questions/7020843/how-to-find-element-by-attribute-value-in-gpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!