Giome Pool Guy
Giome Pool Guy

Reputation: 647

XML - extracting value from specific node

im struggling with extracting value from a specific node in my XML document. Im using w3c.DOM as i have found many tutorials on it but now i cant find any good ones for this task - i had to use XPath for this task instead.

I always know the exact path (and passing it as a string, example: "Car/Wheels/Wheel[@Index=´x´]/" ) leading to a node from which i need to extract a value (a string) and return it (im converting the string into doubles and integers in other methods later). Variable myDoc is Document myDoc.

How do i get this value?

private String xPathValue(String path){

XPath myPath = XPathFactory.newInstance().newXPath();
XPathExpression expr =  xpath.compile(path);  
String result = (String)expr.evaluate(myDoc);  

return result;
}

This however doesnt work and i dont want to create any NodeList since i know the exact paths. Im looking for something that works like Node.getTextContent();

Upvotes: 1

Views: 275

Answers (1)

ug_
ug_

Reputation: 11440

You have 2 options

1) Alter you xPath to return the value of the node instead of the node itself

Using expression: Car/Wheels/Wheel[@Index=´x´]/text()

private String xPathValue(String path) {
    XPath myPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr =  xpath.compile(path);  
    String result = (String)expr.evaluate(myDoc, XPathConstants.STRING);  

    return result;
}

2) Use the same xpath query but return a node type

Using expression: Car/Wheels/Wheel[@Index=´x´]

private String xPathValue(String path) {
    XPath myPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr =  xpath.compile(path);  
    Node result = (Node)expr.evaluate(myDoc, XPathConstants.NODE);  

    return result.getTextContent();
}

Upvotes: 4

Related Questions