C#XML - 反序列化类列表

时间:2017-12-05 11:53:48

标签: c# xml serialization

我正在处理一个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>

我的目标是将其反序列化为 List<DeviceInfo> 变量。

我尝试了以下

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

它在另一个XML文件上为我工作。

更新

与之前的观点相反,事实证明没有错误,列表只是没有填充从XML中提取的值。

1 个答案:

答案 0 :(得分:3)

XML命名空间;在您的xml中,命名空间由xmlns="DeviceInfoCollection"定义 - 但您的代码假定它是空(默认)命名空间。由于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);
}