2015-07-03 26 views
0

我是Xpath的新手,我正在按照教程搜索xml文件中的一些目標數據,並且根據下面發佈的xml文件編寫了以下代碼。並且如下面張貼的結果,我得到了填充有四個空元素的NodeList,我預計節點列表,以四個電子郵件作爲我的搜索表達式填充是搜索表達式返回四個空元素

String expression1 = "/Employees//Employee[position()<=4]//email";

請讓我知道爲什麼我我得到4個null元素

代碼

public static void main(String[] args) throws FileNotFoundException, SAXException, IOException, XPathExpressionException { 

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = null; 

    try { 
     builder = builderFactory.newDocumentBuilder(); 
    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 

    Document document = builder.parse(new FileInputStream("c:\\xml0.xml")); 
    XPath xPath = XPathFactory.newInstance().newXPath(); 

    String expression1 = "/Employees//Employee[position()<=4]//email"; 

    String email = xPath.compile(expression1).evaluate(document); 
    System.out.println(email); 

    Node node = (Node) xPath.compile(expression1).evaluate(document, XPathConstants.NODE); 
    NodeList nodeList = (NodeList) xPath.compile(expression1).evaluate(document, XPathConstants.NODESET); 

    System.out.println(nodeList.getLength()); 
    System.out.println(nodeList.item(0)); 
    System.out.println(nodeList.item(1)); 
    System.out.println(nodeList.item(2)); 
    System.out.println(nodeList.item(3)); 

} 

的Xml

<?xml version="1.0"?> 

<Employees> 
<Employee emplid="1111" type="admin"> 
    <firstname>John</firstname> 
    <lastname>Watson</lastname> 
    <age>30</age> 
    <email>[email protected]</email> 
    </Employee> 

<Employee emplid="2222" type="admin"> 
    <firstname>Sherlock</firstname> 
    <lastname>Homes</lastname> 
    <age>32</age> 
    <email>[email protected]</email> 
</Employee> 

<Employee emplid="4444" type="user"> 
    <firstname>Jim</firstname> 
    <lastname>Moriarty</lastname> 
    <age>52</age> 
    <email>[email protected]</email> 
</Employee> 

<Employee emplid="4444" type="user"> 
    <firstname>Jim</firstname> 
    <lastname>Moriarty</lastname> 
    <age>52</age> 
    <email>[email protected]</email> 
</Employee> 

<Employee emplid="5555" type="admin"> 
    <firstname>Mycroft</firstname> 
    <lastname>Holmes</lastname> 
    <age>41</age> 
    <email>[email protected]</email> 
</Employee> 

</Employees> 

結果

所有的
[email protected] 
4 
[email: null] 
[email: null] 
[email: null] 
[email: null] 

回答

1

我覺得你在表達錯過/text()。嘗試將其更改爲

String expression1 = "/Employees//Employee[position()<=5]/email/text()"; 

否則,代碼看起來沒什麼問題

2

首先,你不需要 「/員工//員工[位置()< = 4] //電子郵件」 在這個XML。 '//'表示任何後代,但在此XML中,員工是員工的直接子代,這意味着一個簡單的'/'就可以做到。

輸出不清零。輸出是節點元素'email',這是你所要求的。

得到你需要使用的文本值: 「/員工/僱員[位置()< = 4] /電子郵件/文本()」