Reputation: 93
I'm working with an XML document which is generated using C# from a list of objects (of the 'People' class)
<?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.
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.
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.
Upvotes: 0
Views: 63
Reputation: 1062945
XML namespaces; in your xml, the namespace is defined by xmlns="DeviceInfoCollection"
- but your code assumes it is the empty (default) namespace. Since xml namespaces are inherited, you need to tell it the namespace throughout:
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);
}
Upvotes: 3