DOM4J: retrieve value of a node filtering by attribute value
Asked Answered
D

2

2

I have a given xml structured like this:

<elem>
     <val id="1">aaa</val>
     <val id="2">bbb</val>
</elem>

With SAXReader (DOM4J), how can I get the value contained into the node with id = 1 ('aaa' in the example)?

I've tried this:

String value = elem.element("val[@id='1']")

where elem is the right "path.current", but it didn't work.

Probably I'm writing the condition with a wrong syntax.. suggestions?

Discobolus answered 22/3, 2011 at 11:27 Comment(1)
Note for others: you must quote the attribute value you're looking for, e.g. "val[@id=1]" won't match anything!Enchant
L
3

The xpath syntax looks fine, but you should use the selectSingleNode method instead.

Node value = elem.selectSingleNode("val[@id='1']/text()");
Lunge answered 22/3, 2011 at 13:14 Comment(0)
W
0

You can try the full XPath: /elem/val[@id='1'] or any parent wildcard //val[@id='1']

Winni answered 22/3, 2011 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.