我有以下 XML 结构
<students>
<student studentnumber="1">
<firstname>Charlie</firstname>
<lastname>Davies</lastname>
<marks>
<first>12</first>
<second>52</second>
<third>98</third>
<forth>32</forth>
</marks>
</student>
<student studentnumber="2">
<firstname>Emily</firstname>
<lastname>Roberts</lastname>
<marks>
<first>55</first>
<second>51</second>
<third>57</third>
<forth>84</forth>
</marks>
</student>
如何构造查询以获取第一个分数超过 50 的学生的名字?我正在这样做,我可以看到有一个结果符合我的预期,但它没有打印出任何内容。
String expression = "/students/student[marks/first > 50]";
NodeList nodes = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
System.out.println(nodes.getLength());
for (int i = 0; i < nodes.getLength(); ++i) {
System.out.println(nodes.item(i).getFirstChild().getNodeValue());
}
谢谢。
最佳答案
您只需要简单地更改您的 Xpath 表达式以遵循:
字符串表达式 = "/students/student[marks/first > 50]/firstname/text()"
你的for循环:
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
输出:
1
Emily
关于Java,XPath - 如何根据特定元素获取整个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49789212/