如何使用Xpath 1.0从XML文档中查找max属性

Her*_*ral 10 xml xpath xpath-1.0

有没有办法查询XML文档以使用Xpath 1.0返回给定属性的最大值?

例如,有没有办法获得最大ID?

<?xml version="1.0" encoding="utf-8"?>
<library>
        <book id="2" name="Dragon Tatoo"/>
        <book id="7" name="Ender's Game"/>
        <book id="3" name="Catch 22"/>
        <book id="1" name="Lord of the rings"/>
</library>
Run Code Online (Sandbox Code Playgroud)

Fre*_*Foo 7

在XPath 2.0中,使用该max功能.要找到最高的书id,做

/library/book[@id = max(/library/book/@id)]
Run Code Online (Sandbox Code Playgroud)

  • 看起来max函数不是Xpath 1.0的一部分:( (2认同)

tim*_*ooo 5

以下 XPath 选择具有最高 id 的书:

/library/book[not(@id <= preceding-sibling::book/@id) and not(@id <=following-sibling::book/@id)]
Run Code Online (Sandbox Code Playgroud)


Jpe*_*per 0

此示例可用于查找最大值。

XmlDocument doc = new XmlDocument();                    
doc.Load("../../Employees.xml");
XmlNode node = doc.SelectSingleNode("//Employees/Employee/@Id[not(. <=../preceding-sibling::Employee/@id) and not(. <=../following-sibling::Employee/@Id)]");
int maxId = Convert.ToInt32(node.Value);
Run Code Online (Sandbox Code Playgroud)

有关 xpath 和 linq 的其他类似主题,请查看http://rmanimaran.wordpress.com/2011/03/20/xml-find-max-and-min-value-in-a-attribute-using-xpath-and-林克/