0
我有一個XML,它看起來像基於成員變量值分割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 [email protected]
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());
}
請提供指導