Xpath没有给出正确的结果

时间:2014-03-25 09:50:17

标签: java xpath xml-parsing

我有一个xml文件,我使用XPATH来解析它。但是我从内容中获取内容时遇到了问题

这是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>

这是我解析它的代码

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());
}

对于此表达式"reg/user",它不返回任何内容,对于"reg/user/Name""reg/user/Email",它返回正确的结果。我用在线测试仪测试了表达,它给出了正确的结果。我的解析代码有蚂蚁问题..?

1 个答案:

答案 0 :(得分:1)

每个user元素的第一个子节点是一个空文本节点,因此您的println语句可能只是打印出来。试一试:

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());
}

虽然这可能更好:

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);
}