Mr.
Mr.

Reputation: 10142

Java - dom4j XPath for children nodes

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).

Upvotes: 3

Views: 8943

Answers (3)

Tomalak
Tomalak

Reputation: 338426

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

The . is the current node in XPath.

Note that // is short for /descendant-or-self::node()/. This means it will also select nested nodes.

You speak of children, which is not the same thing. For child nodes use:

selectNodes("./b") 

Upvotes: 6

josh-cain
josh-cain

Reputation: 5226

Try selectNodes("a//b") if you want all <b> elements, no matter if they are children or children of children. If you want only the <b> elements that are children of <a> use selectNodes("a/b").

If you know that node <a> will be a child of the root node, you can add a / in front to denote that you're only selecting children of the root node like so: selectNodes("/a//b")

See the xpath syntax for more information

Upvotes: 1

Jayy
Jayy

Reputation: 2436

you could use like this

//a/b

and a can be your specific node.

Upvotes: 0

Related Questions