我有xml如下,
<students>
<Student><age>23</age><id>2000</id><name>PP2000</name></Student>
<Student><age>23</age><id>1000</id><name>PP1000</name></Student>
</students>
我有2个xpaths模板XPATH = students/Student
将是模板节点,但是我不能硬编码这个xpath,因为它会改变其他XML,而且XML非常动态,可以扩展(但是相同基础XPATHs)所以,如果我使用模板节点再评估一个XPATH,我使用以下代码,
XPath xpathResource = XPathFactory.newInstance().newXPath();
Document xmlDocument = //creating document;
NodeList nodeList = (NodeList)xpathResource.compile("//students/Student").evaluate(xmlDocument, XPathConstants.NODESET);
for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) {
Node currentNode = nodeList.item(nodeIndex);
String xpathID = "//students/Student/id";
String xpathName = "//students/Student/name";
NodeList childID = (NodeList)xpathResource.compile(xpathID).evaluate(currentNode, XPathConstants.NODESET);
NodeList childName = (NodeList)xpathResource.compile(xpathName).evaluate(currentNode, XPathConstants.NODESET);
System.out.println("node ID " +childID.item(0).getTextContent());
System.out.println("node Name " +childName.item(0).getTextContent());
}
现在的问题是,这个for循环将执行2次,但两次我都得到2000 , PP2000
作为ID值。有没有办法使用针对节点的通用XPATH迭代到子节点。我不能对整个XMLDocument使用通用XPATH,我有一些验证要做。我想使用XML nodelist作为结果集行,以便我可以验证XML值并完成我的工作。
答案 0 :(得分:0)
XPath xpathResource = XPathFactory.newInstance().newXPath();
Document xmlDocument = //creating document;
NodeList nodeList = (NodeList)xpathResource.compile("//students/Student/id").evaluate(xmlDocument, XPathConstants.NODESET);
for (int nodeIndex = 0; nodeIndex < nodeList.getLength(); nodeIndex++) {
Node currentNode = nodeList.item(nodeIndex);
System.out.println("node " +currentNode.getTextContent());
}