XElement and List<T>

让人想犯罪 __ 提交于 2019-12-04 03:14:46

You need to pass the IEnumerable<XElement> query as the second parameter, not the "Author" string, like so:

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

That will give you the result you need.

I know you're using C#, but this is one time when you should seriously consider adding a VB.NET project to your solution. XML Literals are perfect for this and make it much easier.

To get the XML from your Author list, you would do this:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!