Okay so I have this xml:
<employees>
<employee>
<name>John</name>
<surname>Smith</surname>
</employee>
<employee>
<name>Test</name>
<surname>1</surname>
</employee>
<employee>
<name>Cat</name>
<surname>Dog</surname>
</employee>
<employee>
<name>John</name>
<surname>Bravo</surname>
</employee>
</employees>
I am using Xpath to get the child node:
File f = new File("employees.xml");
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document doc = builder.parse(f);
XPath xPath = XPathFactory.newInstance().newXPath();
String val = "John";
String expression = "./employees[employee/name='"+ val +"']";
Node locatedNode = (Node) xPath.evaluate(expression, doc, XPathConstants.NODE);
Nodelist result = locatedNode.getParentNode().getChildNodes();
After that I use a for loop to loop through the nodelist to obtain surname of employees. In this case, I will get the two John's surname and add it to an array list
List<Surname> sname = new ArrayList<Surname>;
for (int i = 0; i < result.getLength(); i++) {
Node nNode = result.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String surname = eElement.getElementsByTagName("surname").item(0).getTextContent();
sname.add(new Surname(surname));
}
}
The problem is i kept on unable to get the Node, it kept throwing nullpointexception error. Is it that my expression is wrong or this line:
Nodelist result = locatedNode.getParentNode().getChildNodes();
is wrong?
What I wanted to get: Smith Bravo
Surnames of both John employee
No comments:
Post a Comment