MRM
MRM

Reputation: 571

How to retrieve a specific node's value in XPath?

I have a XML file with this format:

<object>
<origin>1:1:1</origin>
<normal>2:2:2</normal>
<leafs>
    <object>
        <origin>1:1:1</origin>
        <normal>3:3:3</normal>
        <leafs>none</leafs>
    </object>
</leafs>
</object>

How could I retrieve the value "none" of element <leafs> on second level of the tree? I used this

XPathExpression expLeafs = xpath.compile("*[name()='leafs']");
Object resLeafs = expLeafs.evaluate(node, XPathConstants.NODESET);
NodeList leafsList = (NodeList) resLeafs;
if (!leafsList.item(0).getFirstChild().getNodeValue().equals("none"))
         more code...

but it doesn't work because there are some empty text nodes bofore and after "none". Is there a way to deal with it like xpath.compile("*[value()='none']")?

Upvotes: 0

Views: 356

Answers (2)

MRM
MRM

Reputation: 571

After a checking the code line @Lord Torgamus provided i managed to parse the document as i needed like this:

XPathExpression expLeafs = xpath.compile("*[name()='leafs']");
Object resLeafs = expLeafs.evaluate(node, XPathConstants.NODESET);
NodeList leafsList = (NodeList) resLeafs;

Node nd = leafsList.item(0);

XPathExpression expr = xpath.compile("text()");
Object resultObj = expr.evaluate(nd, XPathConstants.NODE);
String str = expr.evaluate(nd).trim();
System.out.println(str);

and the output is "none" with no other empty text node.

Upvotes: 1

Pops
Pops

Reputation: 30828

I just ran a simple test program using your XML file and

expr = xpath.compile("/object/leafs/object/leafs/text()");

and got the desired "none" result. If you have additional requirements, you'll have to edit your question.

Upvotes: 3

Related Questions