2009-06-09 31 views
9

我有一个映射像的XElement如下:排序的的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> 

我如何通过作者或标题或一年的图书进行排序?谢谢

回答

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); 
+0

我只是想重新排列它。你能提供一个真实世界的例子吗? – pistacchio 2009-06-09 07:10:45

10

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

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); 
    } 
} 

请注意,如果您的根节点下有其他的内容,你应该调用每个XElementRemove加入他们之前,而不是仅仅调用RemoveAll

+1

Darn,我只是打字......我被Skeet狙击了! – jfar 2009-06-09 07:24:30