使用LINQ来填充List< object>.从xml [英] Using LINQ to fill a List<object> from xml

查看:54
本文介绍了使用LINQ来填充List< object>.从xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是LINQ的新手.我需要用来自xml的信息填充以下类的List.

I am new to LINQ. I need to fill a List of the following class with information from xml.

class Person
{
    int id;
    string name;
    string address;
}

List<Person> people = new List<Person>();

在LINQ中执行此操作的正确方法是什么.

What is the correct way to do it in LINQ.

 <Company>
  ...
  ...<!--Lot of items -->
  ...
  <People>      <!--People appears only once -->
        <Instance>
            <ID>1</ID>
            <Name>NameA</Name>
            <Address>AddressA</Address>         
        </Instance>
        <Instance>
            <ID>2</ID>
            <Name>NameB</Name>
            <Address>AddressB</Address>         
        </Instance>
        ..
        ..
 </People>
</Company>

我需要知道LINQ表达式的结构才能直接到达<People>标签.另外,是否存在用于填充List', i.e map Person to Instance`标记的任何快捷方式.

I need to know the structure of LINQ expression to directly reach <People> tag. Also, is there any shortcuts for filling the List', i.e mapPersontoInstance` tag.

推荐答案

我希望您知道您需要将字段(或使其属性更好)公开,以便能够填充对象值.您在班级字段中缺少公共修饰符.

I hope you know that you need to make your fields (or better make them properties) as public to able to fill the object values. You're missing public modifier in your class fields.

var doc = XDocument.Parse(xmlString);
List<People> people = doc.Descendants("People")
                      .FirstOrDefault()
                      .Descendants("Instance")
                      .Select(p=> new Person()
                                  {
                                      ID = p.Element("ID").Value, 
                                      Name = p.Element("Name").Value, 
                                      Address=p.Element("Address").Value
                                   }).ToList();

这篇关于使用LINQ来填充List&lt; object&gt;.从xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆