xpath 遍历子节点
时间: 2023-10-13 10:11:05 浏览: 43
要遍历子节点,可以使用XPath中的“/”和“//”运算符。
- “/”运算符表示选择当前节点的直接子节点。
- “//”运算符表示选择当前节点的所有后代节点。
例如,假设有以下XML文档:
```
<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J.K. Rowling</author>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
</book>
</bookstore>
```
要选择所有书的标题,可以使用以下XPath表达式:
```
/bookstore/book/title
```
这将选择所有直接子节点为“bookstore”的元素,然后选择它们的所有直接子节点为“book”的元素,然后选择它们的所有直接子节点为“title”的元素。
如果要选择所有书的作者,可以使用以下XPath表达式:
```
/bookstore/book/author
```
这将选择所有直接子节点为“bookstore”的元素,然后选择它们的所有直接子节点为“book”的元素,然后选择它们的所有直接子节点为“author”的元素。
如果要选择所有书的标题和作者,可以使用以下XPath表达式:
```
/bookstore/book/*[self::title or self::author]
```
这将选择所有直接子节点为“bookstore”的元素,然后选择它们的所有直接子节点为“book”的元素,然后选择它们的所有直接子节点为“title”或“author”的元素。