【问题标题】:XML node parsing using C# linq使用 C# linq 解析 XML 节点
【发布时间】:2012-08-24 07:07:45
【问题描述】:

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

【问题讨论】:

  • 不确定您要选择什么,但您可以:var result = xDoc.Descendants("demographics");

标签: c# xmldocument


【解决方案1】:
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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    相关资源
    最近更新 更多