开发者

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

How do I select from a par开发者_如何转开发sed html document a specific element given its index.

For example: ...

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

I want to select the second div but it seems to me GPath doesn't offer a solution like Xpath does.


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 on the div node such as .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 sample I listed above but with various content, you can always access the second div using array index 1:

xml.body.div[1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜