-2

i have xml document like this:

<?xml version="1.0" encoding="utf-8" ?> 
<demographics>     
    <country id="1" value="USA">         
        <state id ="1" value="California">             
             <city>Long Beach</city>             
             <city>Los Angeles</city>             
             <city>San Diego</city>         
        </state>         
        <state id ="2" value="Arizona">             
             <city>Tucson</city>             
             <city>Phoenix</city>             
             <city>Tempe</city>         
        </state>     
   </country>     
   <country id="2" value="Mexico">         
      <state id ="1" value="Baja California">             
         <city>Tijuana</city>             
         <city>Rosarito</city>                     
      </state>     
   </country> 
 </demographics> 

How to select everything starting from demographics node using XML linq queries something like this:

var node=from c in xmldocument.Descendants("demographics") ??
L.B
  • 114,136
  • 19
  • 178
  • 224
user1502952
  • 1,390
  • 4
  • 13
  • 27
  • Not sure what you want to select, but you can do: `var result = xDoc.Descendants("demographics");` – Habib Aug 24 '12 at 07:16

1 Answers1

6
XDocument xDoc = XDocument.Parse(xml);
var demographics =  xDoc
        .Descendants("country")
        .Select(c => new
        {
            Country = c.Attribute("value").Value,
            Id = c.Attribute("id").Value,
            States = c.Descendants("state")
                        .Select(s => new
                        {
                            State = s.Attribute("value").Value,
                            Id = s.Attribute("id").Value,
                            Cities = s.Descendants("city").Select(x => x.Value).ToList()
                        })
                        .ToList()
        })
        .ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224