【问题标题】:Trouble in parsing the xml elements using linq in c#在 C# 中使用 linq 解析 xml 元素时遇到问题
【发布时间】:2012-05-28 17:02:39
【问题描述】:

我有一个这样的xml

<rootnode>

<lvl1>AIT</lvl1>

<lvl2>
<a>0</a>
<b> 111</b> 
</lvl2>

</rootnode>

xml解析代码如下

public class accountlist
        {
            public string lvl1 { get; set; }
            public List<string> b { get; set; }                
        } 

List<accountlist> questions = (from c in xmlDoc.Descendants("rootnode")
                                           select new accountlist
                                        {
                                            lvl1 = c.Element("rootnode").Value,
                                            b = (from q in c.Descendants("lvl2").Elements("b").Elements("a") where q.Element("a").Value == "0"
                                                             select q.Value).ToList(),
                                        }).ToList();

我的输出应该是这样的

lvl1 = AIT
b = 111

请帮帮我......

【问题讨论】:

    标签: c#-4.0 linq-to-xml


    【解决方案1】:

    尝试以下查询。

        var doc = XElement.Parse(@"<rootnode><lvl1>AIT</lvl1><lvl2><a>0</a><b> 111</b> </lvl2></rootnode>");
    
        var questions = from c in doc.DescendantsAndSelf("rootnode")
                        select new accountlist
                                   {
                                       lvl1 = c.Element("lvl1").Value,
                                        b = (from q in c.Descendants("lvl2") where q.Element("a").Value == "0"
                                                         select q.Element("b").Value).ToList()
                                   };
    

    看起来您将在结果集中获得一个 b 列表,如果您需要 lvl1 和 b 的简单值,那么

     var question2 = from c in doc.DescendantsAndSelf("rootnode")
                                select new
                                {
                                    lvl1 = c.Element("lvl1").Value,
                                    b =  c.Descendants("lvl2").Elements("b").FirstOrDefault().Value
                                };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多