xPath and max function
I have xml file, and I would like to find node with oldest date.
Is it possible to do it without XLST?
Code:
var xml = @"<books>
<book>
<id>1</id>
<date>2011-01-02</date>
开发者_StackOverflow社区 </book>
<book>
<id>2</id>
<date>2011-02-02</date>
</book>
<book>
<id>3</id>
<date>2011-03-01</date>
</book>
</books>
";
XDocument document = XDocument.Parse(xml);
var result = document.XPathSelectElements("//books/book[max(????)]").ToList();
Thanks,
You can use LINQ to XML, e.g.:
var result = document.Element("books")
.Elements("book")
.OrderByDescending(b => (DateTime)b.Element("date"))
.First();
There wouldn't be a direct way to do this. Some simple algorithm would be.. :
- create date variable pretty with first node's date/
- start iterating through xml
- Read the time .. convert it using
translate
- check if its older than variable.
- if yes update your variable
- Continue reading the xml in ether case until you reach end
try this:
var result = document
.Elements("books")
.Elements("book")
.Elements("date")
.Min(e => DateTime.Parse(e.Value));
Try this.
var booksList = document.Descendants("book")
.Min(b => Convert.ToDateTime(b.Element("date").Value));
精彩评论