如何获得List< type >对象,从这个XML

本文关键字:XML 对象 何获得 List type | 更新日期: 2023-09-27 17:49:14

我看不懂这段代码

        XDocument loaded = XDocument.Load(PATH);
        var devices = new List<Device>(loaded.Descendants("Device").Select(e => new Device
        {
            UserName = "xxx",
            Domain = e.Element("domain").Value,
            FQDN = e.Element("fqdn").Value,
            Password = e.Element("password").Value,
        }));

它如何添加这些元素,并获得设备列表?

如何获得List< type >对象,从这个XML

这段代码使用LINQ读取XML并使用XML的信息创建一个Device对象列表。

像这样填充字段:

  • UserName = "xxx"始终UserName属性具有相同的值xxx
  • Domain = xml
  • 中域元素的值
  • FQDN = XML中FQDN元素的值
  • Password = xml
  • 中Password元素的值

你的XML是这样的:

<Devices>
  <Device>
    <domain>domainValue</domain>
    <fqdn>fqdnValue</fqdn>
    <password>passwordValue</password>
  </Device>
</Devices>
    XDocument loaded = XDocument.Load(PATH);
      // devices = List of device
    var devices = new List<Device>
      //look up for every Device in xml file
    (loaded.Descendants("Device")
      //create new Device object
    .Select(e => new Device
    {
          //and fill it with found element's values
        UserName = "xxx",
        Domain = e.Element("domain").Value,
        FQDN = e.Element("fqdn").Value,
        Password = e.Element("password").Value,
    }));