Java - dom4j XPath for children nodes

Mr. picture Mr. · Oct 17, 2012 · Viewed 8.5k times · Source

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

Answer

Tomalak picture Tomalak · Oct 17, 2012
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")