Skip to main content
 首页 » 编程设计

c#之linq读取xml文件

2024年02月20日12java哥

我有如下的 xml 文件和 Device类,我想得到 List<Device>从我的 xml 文件 我如何通过 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> 

请您参考如下方法:

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 
                                                         )));