2014-07-10 106 views
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()); 
    } 

請提供指導

回答

0

您的XPath表達式會選取一個<company>,其中至少有其中一個名字爲Peter的職員。

你真正想要的是在<staff>級別挑:

company/staff[firstname = 'Peter']