2009-07-14 14 views
8

我有一個具有以下屬性的類:的XElement和列表<T>

public class Author { 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

接下來,我有作者的列表,像這樣:

List<Author> authors = new List<Author>(); 

authors.add(
    new Author { 
    FirstName = "Steven", 
    LastName = "King" 
    }); 

authors.add(
    new Author { 
    FirstName = "Homer", 
    LastName = "" 
    }); 

現在,我嘗試使用Linq到XML,以便生成代表作者列表的XML。

new XElement("Authors", 
    new XElement("Author", 
    from na in this.Authors 
    select new XElement("First", na.First))) 

上面的塊並不像我期望的那樣生成XML。我得到的是:

<Authors> 
    <Author> 
    <First>Steven</First> 
    <First>Homer</First> 
    </Author> 
<Authors> 

我想要的XML輸出,怎麼看起來象是:

<Authors> 
    <Author> 
    <First>Steven</First> 
    <Last>King</Last> 
    </Author> 
    <Author> 
    <First>Homer</First> 
    <Last></Last> 
    </Author> 
</Authors> 

如何讓XML來看看,因爲我需要它的任何幫助將非常感激!

回答

11

您需要通過IEnumerable<XElement>查詢作爲第二個參數,而不是「作者」的字符串,像這樣:

// Note the new way to initialize collections in C# 3.0. 
List<Author> authors = new List<Author>() 
{ 
    new Author { FirstName = "Steven", LastName = "King" }), 
    new Author { FirstName = "Homer", LastName = "" }) 
}; 

// The XML 
XElement xml = new XElement("Authors", 
    from na in this.Authors 
    select new XElement("Author", 
     new XElement("First", na.FirstName), 
     new XElement("Last", na.LastName))); 

這會給你你需要的結果。

2

我知道你在使用C#,但是這是一次你應該認真考慮在你的解決方案中添加一個VB.NET項目。 XML文字是完美的,並使其更容易。

爲了讓您的作者名單的XML,你可以這樣做:

Function GetAuthorsXML(authors As List(Of Author)) As XElement 
    Return <Authors> 
       <%= from a in authors _ 
        select <Author> 
           <First><%= a.FirstName %></First> 
           <Last><%= a.LastName %></Last> 
          </Author> %> 
      </Authors> 
End Function 
+1

有一個*完全獨立的項目*只是爲了XML魔法有點過大,最好的。除非必須完成大量的XML轉換(並且具有更復雜的性質),否則添加另一個程序集(除非要編譯爲模塊,然後將它們編織在一起,這是另一個PITA),只是增加了太多開銷在很多領域。 – casperOne 2013-03-05 15:12:46