试图通过获取childnode值获取nodeList

时间:2014-07-13 15:39:51

标签: java xml xpath

好的,我有这个xml:

<employees>
   <employee>
     <name>John</name>
     <surname>Smith</surname>
     <age>18</age>
   </employee>
  <employee>
     <name>Test</name>
     <surname>1</surname>
     <age>18</age>
  </employee>
  <employee>
     <name>Cat</name>
     <surname>Dog</surname>
     <age>18</age>
   </employee>
   <employee>
     <name>John</name>
     <surname>Bravo</surname>
     <age>19</age>
   </employee>
</employees>

我正在使用Xpath来获取子节点:

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

之后我使用for循环遍历nodelist以获取员工的姓氏。 在这种情况下,我将获得两个John的姓氏,并将其添加到数组列表

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

问题是我一直无法获取Node,它一直抛出nullpointexception错误。 这是我的表达错误还是这一行:

Nodelist result = locatedNode.getParentNode().getChildNodes();

错了?

我想得到的(姓氏和年龄)基于姓氏(约翰): 史密斯18 Bravo 19

John员工的姓氏

1 个答案:

答案 0 :(得分:1)

这些行完成了查找surname个节点的工作:

String expression = "./employees/employee[name='"+ val +"']/surname";
NodeList result = (NodeList) xPath.evaluate(expression, doc, XPathConstants.NODESET);

然后您可以提取文本值,例如

for (int i = 0; i < result.getLength(); i++)
{  
  Node node = result.item(i);
  System.out.println(node.getTextContent() ); 
} // end for i

UPD。如果有几个感兴趣的子节点,那么XPath评估可以分两步完成:首先在文档级别,然后在节点级别:

String expression = "./employees/employee[name='"+ val +"']";
NodeList elements = (NodeList) xPath.evaluate(expression, doc, XPathConstants.NODESET);
for (int i = 0; i < elements.getLength(); i++)
{  
  Node node = elements.item(i);
  Node surname = (Node) xPath.evaluate("surname", node, XPathConstants.NODE);
  Node age = (Node) xPath.evaluate("age", node, XPathConstants.NODE);
  System.out.println(surname.getTextContent() + " " + age.getTextContent() );
} // end for i