开发者

xPath and max function

开发者 https://www.devze.com 2023-03-28 16:52 出处:网络
I have xml file, and I would like to find node with oldest date. Is it possible to do it without XLST?

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.. :

  1. create date variable pretty with first node's date/
  2. start iterating through xml
  3. Read the time .. convert it using translate
  4. check if its older than variable.
  5. if yes update your variable
  6. 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));
0

精彩评论

暂无评论...
验证码 换一张
取 消