我有一个看起来像
的xml<?xml version="1.0"?>
<company>
<staff>
<firstname>John</firstname>
<lastname>Player</lastname>
<nickname>JP</nickname>
<salary>1000</salary>
</staff>
<staff>
<firstname>Peter</firstname>
<lastname>Shaw</lastname>
<nickname>PS</nickname>
<salary>2000</salary>
</staff>
</company>
我只需要在名字是彼得时选择,即我的o / p应该是:
<staff>
<firstname>Peter</firstname>
<lastname>Shaw</lastname>
<nickname>PS</nickname>
<salary>2000</salary>
</staff>
我正在使用XPath,示例代码如下:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("./company[staff/firstname = 'Peter']");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("Print " + result); //comes as com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList@ef0cdb
NodeList nodes = (NodeList) result;
System.out.println("Size"+ nodes.getLength()); // comes as 0
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
请提供指导
答案 0 :(得分:0)
您的XPath表达式将选择一个{em}至少至少一名名为Peter的职员。{/ p>
您真正想要的是选择<company>
级别:
<staff>