注意:以下信息假定使用 XPath 1.0。
以下表达式返回具有最大值的元素id
:
/*/book[not(@id < preceding-sibling::book/@id) and
not(@id < following-sibling::book/@id)]
请注意,这与@timbooo 的答案略有不同,因为当存在具有相同最大值的重复项时,这将返回多个元素(@timbooo 将返回无)。如果在这种情况下您只需要一个元素,那么您需要一个解决策略。要选择文档顺序中的第一个此类元素,请使用以下命令:
/*/book[not(@id < preceding-sibling::book/@id) and
not(@id < following-sibling::book/@id)][1]
要选择最后一个,请使用:
/*/book[not(@id < preceding-sibling::book/@id) and
not(@id < following-sibling::book/@id)][last()]
这种方法非常低效(O(n^2)
),因为它要求您将每个元素与每个其他潜在最大值进行比较。因此,最好使用宿主编程语言来选择最大元素。只需book
先选择所有元素,然后从该列表中选择最大值。这(很可能)是一个线性运算 ( O(n)
),它在非常大的文档上会明显更快。例如,在 Java (JAXP) 中,您可能会这样做:
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate("/*/book", doc,
XPathConstants.NODESET);
Node max = nodes.item(0);
for (int i = 0; i < nodes.getLength(); i++) {
int maxval = Integer.parseInt(max.getAttributes()
.getNamedItem("id").getNodeValue());
int curval = Integer.parseInt(nodes.item(i).getAttributes()
.getNamedItem("id").getNodeValue());
if (curval >= maxval)
max = nodes.item(i);
}
System.out.println(max.getAttributes().getNamedItem("name"));
请注意,这只是一个演示;确保在适当的地方包括空检查。