Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XElement and List<T>

I have a class that has the following properties:

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

Next, I have a List of Authors like so:

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

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

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

Now, I am trying to use Linq to XML in order to generate the XML representing my Authors List.

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

The block above does not generate the XML as I expect it to. What I get is:

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

What I want the XML output to look like is:

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

Any help on how to get the XML to look as I need it to would be immensely appreciated!

like image 497
Jagd Avatar asked Jul 14 '09 19:07

Jagd


2 Answers

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.

like image 191
casperOne Avatar answered Sep 21 '22 14:09

casperOne


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
like image 42
CoderDennis Avatar answered Sep 21 '22 14:09

CoderDennis