Mort Mort - 3 months ago 9
C# Question

Empty List when deserializing XML to Object

I am having problems deserializing XML to an object with a list. The deserialize runs without error but the Resources list is empty, and I know there is one resource returned in the XML. It seems like it is just not being deserialised properly.

I am using the following code to deserialize

var ser = new XmlSerializer(typeof(SearchResult));
var test = result.Content.ReadAsStringAsync();
var t = (SearchResult)ser.Deserialize(result.Content.ReadAsStreamAsync().Result);


The variable "test" on line 2 of the code above is equal to

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<ns3:searchResult total="1" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ns3="ers.ise.cisco.com">
<resources>
<resource id="76a4b0f2-64e2-11e6-9f15-00505688a404" name="5555884552">
<link rel="self" href="https://servername123:9060/ers/config/guestuser/76a4b0f2-64e2-11e6-9f15-00505688a404" type="application/xml"/>
</resource>
</resources>
</ns3:searchResult>




So I would expect to get one ExistingWifiAccountDto in the Resources list. But I don't. It is empty. What am I doing wrong?

The classes for object mapping are below

[XmlRoot(ElementName = "searchResult", Namespace = "ers.ise.cisco.com")]
public class SearchResult
{
public SearchResult()
{
Resources = new List<ExistingWifiAccountDto>();
}

[XmlArray("resources")]
[XmlArrayItem("resource", typeof(ExistingWifiAccountDto))]
public List<ExistingWifiAccountDto> Resources { get; set; }
}

public class ExistingWifiAccountDto
{
public ExistingWifiAccountDto()
{
}

[XmlAttribute("id")]
public string Id { get; set; }
[XmlAttribute("name")]
public string Name { get; set; }
[XmlElement("link")]
public LinkDto Link { get; set; }
}

public class LinkDto
{
public LinkDto()
{
}

[XmlAttribute("rel")]
public string Rel { get; set; }
[XmlAttribute("href")]
public string Href { get; set; }
[XmlAttribute("type")]
public string Type { get; set; }
}

Answer

You'll have to set the namespace to an empty string for the "resources" array since it is not inherited in you situation. This should then flow down to child elements.

Try changing

[XmlArray("resources")]

to

[XmlArray("resources", Namespace = "")]

This will cause it to deserialize correctly, alternatively, you could also set each node from "resources" down with the Form attribute:

Form = XmlSchemaForm.Unqualified

Cheers

Comments