2014-07-13 129 views
0

好讓節點列表,所以我有這樣的XML:試圖通過越來越childnode價值

<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循環循環訪問節點列表以獲取員工的姓氏。 在這種情況下,我會得到兩個約翰的姓,並把它添加到一個數組列表

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

問題是我一直無法得到的節點,它一直扔nullpointexception錯誤。 是我的表情是錯的還是這條線:

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

是不對?

我想基於姓(約翰)得到(姓&歲): 史密斯18 布拉沃19

兩個約翰員工的姓氏

回答

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 
+0

謝謝,如果內部員工,有什麼例子等元素,年齡和性別,我想獲得他們的價值。我怎麼做,這只是姓氏。 – edward

+0

如果我想要獲得編輯問題中描述的其他元素,我該怎麼做。謝謝! – edward