Search code examples
c#linqxelement

XElement to List in c#


I want to convert XElement to my Object List. I have "Car" object and in help function i create XElement When i convert it with linq i get empty List. here is what i wrote:

public class Car
{
    public int row{ get; set; };
    public int seat{ get; set; }

    public Car()
    {

    }
}

public static void help()
    {
        XElement root = new XElement("Car",
            new XElement("seat", 
            new XElement("row", "4"),
            new XElement("Chair", "2")),

            new XElement("seat", 
            new XElement("row", "3"),
            new XElement("Chair", "2")),

            new XElement("seat",
            new XElement("row", "5"),
            new XElement("Chair", "2"))
            );


        List<Seat> a = root.Elements("Car").Select(s=>s.Element("seat")).Select(sv => new Car()    
        {
            row= (int)sv.Element("row"),
            seat= (int)sv.Element("Chair")
        }).ToList();
}

Solution

  • List<Car> list = root.Elements("seat").Select(sv => new Car()
    {
        row = (int)sv.Element("row"),
        seat = (int)sv.Element("Chair")
    }).ToList();
    

    With root you are already "inside" the Car element.

    Note that you could create a full XDocument:

    var doc = new XDocument(root);
    
    List<Car> list2 = doc.Elements("Car").Elements("seat").Select(sv => new Car()
    {
        row = (int)sv.Element("row"),
        seat = (int)sv.Element("Chair")
    }).ToList();
    

    In this way, doc would be "outside" the Car element.

    You could then even:

    List<Car> list3 = doc.Root.Elements("seat").Select(sv => new Car()
    {
        row = (int)sv.Element("row"),
        seat = (int)sv.Element("Chair")
    }).ToList();