由linq读取xml文件

时间:2012-08-15 02:38:18

标签: c# linq linq-to-xml

我有像下面和Device类这样的xml文件,我希望从我的xml文件中获取List<Device> 我怎么能通过linq做到这一点

            XDocument loaded = XDocument.Load(SharedData.CONFIGURATION_FULL_PATH);
            var q = loaded.Descendants("device").Select(c => c);

但当然这段代码不起作用

<?xml version="1.0" encoding="utf-8"?>
<settings>
<device>
  <username>aa</username>
  <AgentName>aa</AgentName>
  <password>aa</password>
  <domain>aa</domain>
</device>
<device>
  <username>bb</username>
  <AgentName>bb</AgentName>
  <password>bb</password>
  <domain>bb</domain>
</device>
<device>
  <username>cc</username>
  <AgentName>cc</AgentName>
  <password>cc</password>
  <domain>cc</domain>
</device>

</settings>

2 个答案:

答案 0 :(得分:4)

List<Device> devices = new List<Device>(loaded.Descendants("Device")
                                             .Select(e =>
                                               new Device(e.Element("username").Value,
                                                          e.Element("AgentName").Value,
                                                          e.Element("password").Value,
                                                          e.Element("domain").Value
                                                         )));

答案 1 :(得分:0)

你可以这样做:

var devices =
    loaded
        .Descendants("Device")
        .Select(e => new Device(
            e.Element("username").Value,
            e.Element("AgentName").Value,
            e.Element("password").Value,
            e.Element("domain").Value))
        .ToList();