-2

我有这样的xml文档:

<?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> 

如何使用 XML linq 查询从人口统计节点开始选择所有内容,如下所示:

var node=from c in xmldocument.Descendants("demographics") ??
4

1 回答 1

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();
于 2012-08-24T07:11:33.857 回答