3

I am using [dom4j]1 and [XPath]2 in order to traverse an XML.

Assume I have in hand a Node which has children nodes, each of which has the same tag name. e.g. (refer to the b node):

<a>
    <b>...</b>
    <b>...</b>
</a>

I tried to use selectNodes("//b") but it returns all of the nodes within the document which their open tag is b.

How can I traverse only the children nodes of a specific node, where all the children nodes have the same tag name (e.g. b).

4

3 回答 3

6
selectNodes(".//b") 
//-----------^

.是 XPath 中的当前节点。

请注意,它///descendant-or-self::node()/. 这意味着它还将选择嵌套节点。

你说的是孩子,这不是一回事。对于子节点使用:

selectNodes("./b") 
于 2012-10-17T14:29:24.777 回答
1

尝试selectNodes("a//b") 如果您想要所有<b>元素,无论它们是孩子还是孩子的孩子。如果你只想要use<b>的子元素。<a>selectNodes("a/b")

如果您知道该节点<a>将是根节点的子节点,则可以在前面添加 / 表示您只选择根节点的子节点,如下所示:selectNodes("/a//b")

有关详细信息,请参阅xpath 语法

于 2012-10-17T14:32:01.493 回答
0

你可以这样使用

//a/b

并且a可以是您的特定节点。

于 2012-10-17T14:31:50.420 回答