Reputation: 121
I am trying to read the lines of an XML file using the XPath library. So far I have been able to read each of the nodes of the document that I am processing but I don't know how to access a specific attribute of the node.
For a better understanding, I will give an example along with the code I have developed so far:
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
<string key1="/path" key2="title" key3="English" value="Spanish"/>
What I want to do is get the value of the value attribute that in the example all nodes contain the text "Spanish".
With the following code I read each of the lines but I don't know how to access the value of the attributes with the Java XPath library:
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
String xPathExpression = "//string";
Document documento = null;
NodeList nodos = null;
try {
// Carga del documento xml
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
documento = builder.parse(new File("./src/TestResults/xmlFile.lang"));
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
// Preparación de xpath
XPath xpath = XPathFactory.newInstance().newXPath();
// Consultas
nodos = (NodeList) xpath.evaluate(xPathExpression, documento, XPathConstants.NODESET);
} catch (Exception e) {
System.out.println(e.getMessage());
}
for (int i=0;i<nodos.getLength();i++){
System.out.println("********* ITER " + i + " *********");
System.out.println(nodos.item(i).getNodeName());
System.out.println(nodos.item(i).getNodeValue());
System.out.println(nodos.item(i).getAttributes());
System.out.println("**************************");
}
}
Upvotes: 0
Views: 285
Reputation: 4088
Try
nodos.item(i).getAttributes().getNamedItem("value").getNodeValue();
Upvotes: 1
Reputation: 12817
It's a bit unclear what you want to achieve, but if you want the value of the 'value' attribute, the XPath expression could be:
//string/@value
where '@' is shorthand for the attribute
axis`. Could also be written as
//string/attribute::value
Upvotes: 2