简体   繁体   English

C#XML-反序列化类列表

[英]C# XML - Deserializing a list of classes

I'm working with an XML document which is generated using C# from a list of objects (of the 'People' class) 我正在使用XML文档,该文档是使用C#从“ People”类的对象列表中生成的

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDeviceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="DeviceInfoCollection">
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000001</SerialID>
    <AzureID>2d680cd1-7320-43a9-87d4-75a2698771a3</AzureID>
    <FirmwareVersion>3.0.0</FirmwareVersion>
  </DeviceInfo>
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000002</SerialID>
    <AzureID>646ca461-9352-4746-9fa6-6308010059fb</AzureID>
    <FirmwareVersion>1.1.2</FirmwareVersion>
  </DeviceInfo>

My goal is to deserialize this back into a List<DeviceInfo> variable. 我的目标是将其反序列化回 List<DeviceInfo> 变量。

I've tried the following 我尝试了以下

            var xDoc = XDocument.Load(Application.StartupPath + "/devicesTEST.xml");
            if (File.ReadAllText(Application.StartupPath + "/devicesTEST.xml").Length > 0)
            {

                var envs = from e in xDoc.Root.Descendants("DeviceInfo")
                           select new DeviceInfo
                           {
                               SerialID = (string)e.Element("SerialID"),
                           };
                Manager.Devices = envs.ToList();
            }

and it's working for me on another XML file. 它在另一个XML文件上为我工作。

Update 更新

Contrary to previous belief, it turns out there is no error, the list just doesn't get populated with the values extracted from the XML. 与以前的看法相反,事实证明没有错误,该列表只是没有填充从XML中提取的值。

XML namespaces; XML名称空间; in your xml, the namespace is defined by xmlns="DeviceInfoCollection" - but your code assumes it is the empty (default) namespace. 在您的xml中,名称空间是由xmlns="DeviceInfoCollection"定义的-但是您的代码假定它是空的(默认)名称空间。 Since xml namespaces are inherited, you need to tell it the namespace throughout: 由于xml命名空间是继承的,因此您需要在整个过程中将其命名为:

XNamespace ns = "DeviceInfoCollection";
var devices = from e in xDoc.Root.Descendants(ns + "DeviceInfo")
           select new DeviceInfo
           {
               SerialID = (string)e.Element(ns + "SerialID"),
           };

foreach(var device in devices)
{
    Console.WriteLine(device.SerialID);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM