2009-06-09 34 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