Reputation: 3050
i have an xml file and i am using XPATH to parse it. But i am having problem while getting contents out of it
here is the xml
<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
<reg>
<user>
<Name>abc def</Name>
<Email>ahjkhjkghjkhjk</Email>
<Picture>/mnt/sdcard/download/1357670177a386a-big-1.jpg</Picture>
<LastEdited>Mar 12, 2014 10:32:09 AM</LastEdited>
</user>
<user>
<Name>xy zabc</Name>
<Email>asdasdasdasd</Email>
<Picture>/mnt/sdcard/download/1357670177a386a-big-1.jpg</Picture>
<LastEdited>Mar 12, 2014 10:32:09 AM</LastEdited>
</user>
</reg>
and here is my code for parsing it
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/reg/user/Name";
System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
Users_List.add(nodeList.item(i).getFirstChild().getNodeValue());
}
for this expression "reg/user"
it return nothing and for "reg/user/Name"
or "reg/user/Email"
it returns correct result. i have tested expression with online tester there it gives correct result. is there ant problem with my parsing code..?
Upvotes: 0
Views: 63
Reputation: 101748
The first child of each of your user
elements is an empty text node, so your println
statements are probably just printing out nothing. Give this a try:
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getChildNodes()[1].getTextContent());
Users_List.add(nodeList.item(i).getChildNodes()[1].getTextContent());
}
though this is probably better:
for (int i = 0; i < nodeList.getLength(); i++) {
String name = "";
NodeList nameList = (NodeList)xPath.evaluate("Name", nodeList.items(i),
XPathConstants.NODE);
if(nameList.getLength() > 0) {
name = nameList.items(0).getTextContent();
}
System.out.println(name);
Users_List.add(name);
}
Upvotes: 1