ar.gorgin
ar.gorgin

Reputation: 5002

Reading XML using XDocument & Linq

I have a xml file like this :

<root>
 <lv1 value="a" >
  <lv2 value="aa" >
   <lv3 name="aaa" value="1" />
   <lv3 name="aab" value="2" />
   <lv4 name="aac" value="4" />
  </lv2>
 <lv2 value="bb">
  <lv3 name="bba" value="2" />
  <lv3 name="bbb" value="5" />
  <lv3 name="bbc" value="4" />
 </lv2>
</lv1>

</root>

I want find all value and name of lv3 that lv2.value="bb" and lv1.value="a"

I use linq for it

 var lv1s = from lv1 in XDocument.Load(yourPath)
                                 .Descendants("lv1")
                                 .Descendants("lv2")
                                 .Descendants("lv3")
             select new
             {
                 value = lv1.Attribute("value").Value,
                 name = lv1.Attribute("name").Value
             };

  foreach (var lv in lv1s)
  {
      holiday += lv.name +":" + lv.name     ;
  }

How do set where for it ???

Upvotes: 1

Views: 3624

Answers (1)

cuongle
cuongle

Reputation: 75306

 var result = XDocument.Load(yourPath).Descendants("lv1")
            .Where(x => x.Attribute("value").Value == "a")
            .Descendants("lv2")
            .Where(x => x.Attribute("value").Value == "bb")
            .Descendants("lv3")
            .Select(x => new
                {
                    Name = x.Attribute("name").Value,
                    Value = x.Attribute("value").Value
                });

Upvotes: 2

Related Questions