XElement和List

我有一个具有以下属性的类:

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

接下来,我有一个像这样的作者列表:

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

现在,我正在尝试使用Linq to XML来生成表示我的作者列表的XML。

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

上面的块不会像我期望的那样生成XML。 我得到的是:

   Steven Homer   

我希望XML输出看起来像是:

   Steven King   Homer    

任何有关如何让XML看起来像我需要它的帮助将非常感激!

您需要将IEnumerable查询作为第二个参数传递,而不是“作者”字符串,如下所示:

 // Note the new way to initialize collections in C# 3.0. List authors = new List () { 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))); 

这将为您提供所需的结果。

我知道您正在使用C#,但这是您应该认真考虑在解决方案中添加VB.NET项目的一次。 XML Literals非常适合这一点并使其更容易。

要从作者列表中获取XML,您可以这样做:

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