JDS February 2016

Learning Linq to XML and trying to create an object from xml nodes

I am in the process of learning LINQ to XML.

Say I have an xml like this:

<main>
    <machine>
            <car name="HONDA">
                <model name="ACCORD"/>
            </car>
            <car name="HONDA">
                <model name="CRV"/>
            </car>
            <car name="FORD">
                <model name="FOCUS"/>
            </car>
            etc.......        
    </machine>
</main>

I have an object called:

public class MyCar
{
    public MyCar() { }
    public MyCar(string m1, string m2)
    {
        Make = m1;
        Model = m2;
    }

    public string Make { get; set; }
    public string Model{ get; set; }
}

Using LINQ how can I accomplish setting the "Model" in my statement?

    var cars = from g in doc.Elements("main").Descendants("machine")
                 select g;
    var listCars = from c in cars.Descendants("car")
                 select new MyCar
                 {
                     Make = c.Attribute("name").Value,
                     Model= ""
                 };

I am using 4.0 framework.

Answers


octavioccl February 2016

You could use Element method:

var listCars = from c in cars.Descendants("car")
               select new MyCar
               {
                  Make = c.Attribute("name").Value,
                  Model= c.Element("model").Attribute("name").Value
               };

Update

If you change your xml schema to something like you show in your comment, you can filter your cars, for example, this way:

var listCars = from c in cars.Descendants("car")
               let doors= c.Elements("model").FirstOrDefault(e=>e.Attribute("name").Value=="doors")
               where doors!=null && doors.Value=="4 Doors"// this way you can get the cars that only have 4 doors
               select new MyCar
               {
                  Make = c.Attribute("name").Value,
                 //...
               };

Post Status

Asked in February 2016
Viewed 3,332 times
Voted 6
Answered 1 times

Search




Leave an answer