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


i in process of learning linq xml.

say have xml 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 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 accomplish setting "model" in statement?

    var cars = g in doc.elements("main").descendants("machine")                  select g;     var listcars = c in cars.descendants("car")                  select new mycar                  {                      make = c.attribute("name").value,                      model= ""                  }; 

i using 4.0 framework.

you use element method:

var listcars = c in cars.descendants("car")                select new mycar                {                   make = c.attribute("name").value,                   model= c.element("model").attribute("name").value                }; 

update

if change xml schema show in comment, can filter cars, example, way:

var listcars = c in cars.descendants("car")                let doors= c.elements("model").firstordefault(e=>e.attribute("name").value=="doors")                doors!=null && doors.value=="4 doors"// way can cars have 4 doors                select new mycar                {                   make = c.attribute("name").value,                  //...                }; 

Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -