我是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]