对XElement进行排序

时间:2009-06-09 07:01:14

标签: .net linq

我有一个XElement,其映射如下:

<book>
    <author>sadfasdf</author>
    <title>asdfasdf</title>
    <year>1999</year>
</book>
<book>
    <author>asdfasdf</author>
    <title>asdfasdf</title>
    <year>1888</year>
</book>
<book>
    <author>asdfsdf</author>
    <title>asdfasdf</title>
    <year>1777</year>
</book>

如何按作者或标题或年份对书籍进行排序?感谢

2 个答案:

答案 0 :(得分:12)

您是否希望以特定顺序读取(查询)数据,或者您是否真的想要重新排序xml中的数据?要按特定顺序阅读,只需使用LINQ OrderBy方法:

    var qry = from book in el.Elements("book")
              orderby (int)book.Element("year")
              select new
              {
                  Year = (int)book.Element("year"),
                  Title = (string)book.Element("title"),
                  Author = (string)book.Element("author")
              };

(已编辑)更改xml更棘手......可能是这样的:

    var qry = (from book in el.Elements("book")
               orderby (int)book.Element("year")
               select book).ToArray();

    foreach (var book in qry) book.Remove();
    foreach (var book in qry) el.Add(book);

答案 1 :(得分:11)

这是可行的,但有点奇怪:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        string xml = 
@"<books>
  <book>
    <author>sadfasdf</author>
    <title>asdfasdf</title>
    <year>1999</year>
  </book>
  <book>
    <author>asdfasdf</author>
    <title>asdfasdf</title>
    <year>1888</year>
  </book>
  <book>
    <author>asdfsdf</author>
    <title>asdfasdf</title>
    <year>1777</year>
  </book>
</books>";
        XElement root = XElement.Parse(xml);

        List<XElement> ordered = root.Elements("book")
            .OrderBy(element => (int)element.Element("year"))
            .ToList();

        root.ReplaceAll(ordered);
        Console.WriteLine(root);
    }
}

请注意,如果您的根节点下有其他内容,则应在添加Remove之前调用XElement,而不是仅调用RemoveAll