简体   繁体   中英

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.

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,
                 //...
               };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM