Я новичок в Xpath
, и я следовал учебному курсу для поиска некоторых целевых данных в XML-файле, и я написал следующий код в соответствии с ниже размещенным XML-файлом. и, как показано в опубликованных результатах ниже, я получил Nodelist населенного с четырьмя нулевыми элементами, и я ожидал, что NodeList заселяться с четырьмя писем, как мое выражение поиска являетсявыражение поиска возвращает четыре нулевые элементы
String expression1 = "/Employees//Employee[position()<=4]//email";
пожалуйста, дайте мне знать, почему я я получаю четыре нулевых элементов
код:
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]