使用C#linq解析XML节点

时间:2012-08-24 07:07:46

标签: c# xmldocument

我有这样的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") ??

1 个答案:

答案 0 :(得分: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();