<response version-api="2.0">
<value>
<books>
<book available="20" id="1">
<title>Don Quixote</title>
<author id="1">Miguel de Cervantes</author>
</book>
<book available="14" id="2">
<title>Catcher in the Rye</title>
<author id="2">JD Salinger</author>
</book>
<book available="13" id="3">
<title>Alice in Wonderland</title>
<author id="3">Lewis Carroll</author>
</book>
<book available="5" id="4">
<title>Don Quixote</title>
<author id="4">Miguel de Cervantes</author>
</book>
</books>
</value>
</response>
内置方法
以node
表示当前获取到的节点
GPathResult对应Api:http://groovy-lang.org/api.html
- 获取当前节点名称
node.name
- 获取当前节点文本内容
String str = node.text()
# 将文本内容转换Integer、Float、BigInteger
str.toInteger()
str.toFloat()
str.toBigInteger()
- 获取当前同级节点个数
node.size()
- 在节点集中查找一个节点
nodeList.find {
node -> node.name() == 'book' && node.@id == '2'
}
- 在节点集中找到满足条件的所有节点
nodeList.findAll {
book -> book.@id.toInteger() > 2
}*.title
获取第一本书的作者姓名
response.value.books.book[0].author.text()
books
下有多个book
,GPath
索引从0
开始
想要取某些相同字段中的最后一个,可以使用 -1
作为索引
获取某节点的属性
esponse.value.books.book[0].author['@id']
第一本书的作者的id
属性
也可以使用以下表达方式:
esponse.value.books.book[0].author.'@id'
esponse.value.books.book[0].author.@id
便捷获取子节点(*)、子孙节点(**)
- .children()
response.value.books.'*'.find {
node -> node.name() == 'book' && node.@id == '2'
}
查找books
下的名为book
且属性id为2的子节点
*
表示当前节点下的直接子节点
上述表达式也可写为
response.value.books.children().find {
node -> node.name() == 'book' && node.@id == '2'
}
- .depthFirst()
当只知道作者名为Lewis Carroll,但是并不知道他的层级等其他信息,可如下使用
response.'**'.find {
book -> book.author.text() == 'Lewis Carroll'
}.@id
上述表达式也可写为
response.depthFirst().find {
book -> book.author.text() == 'Lewis Carroll'
}.@id