I need a GPath query to select a node using a numeric index

How to choose a specific element from the analyzed html-document taking into account its index.

For instance: ...

<div>div1</div> <div>div2</div> 

I want to select the second div , but it seems to me that GPath does not offer a solution like Xpath.

+4
source share
1 answer
 def html = """ <html> <head> <title>test</title> </head> <body> <div>div1</div> <div>div2</div> </body> </html>""" def xml = new XmlSlurper().parseText(html) assert xml.body.div[0].text() == "div1" assert xml.body.div[1].text() == "div2" 

You can also use collection type methods in div node, e.g. .each / .find, for example:

 xml.body.div.find { it.text() == "div2" } 

EDIT:

To clarify my answer a bit, given HTML in the same structure as the above sample, but with different content, you can always access the second div using array index 1:

 xml.body.div[1] 
+7
source

Source: https://habr.com/ru/post/1334455/


All Articles