When deserializing an array in C#, the element is always null.
When deserializing partially works, I have an issue. When I have an XML node with attributes, it loads all of the attribute data into my class correctly, but when I utilize elements, it just returns null.
In an XML file, I have the following information:
<?xml version="1.0" encoding="ISO8859-1"?> ... <numbers> <number id="55">name1</number> <number id="4">name2</number> </numbers> ...
The following is how the class is defined:
public class root { [XmlArray("numbers")] [XmlArrayItem(ElementName = "number")] public List<NumberObj> numbers { get; set; } } [Serializable] public class NumberObj { [XmlElement] public string name { get; set; } [XmlAttribute("id")] public string id { get; set; } }
The name, on the other hand, remains empty. I’ve tried everything from changing the list to an array, but the name is always null.
I can see that the above class is incorrect because I receive the following when I serialize it back to XML:
<numbers> <number id="123"> <number>abc</number> </number> <number id="45"> <number>abc</number> </number> </numbers>
Is there anyone that could put me in the correct direction?
Thanks
Add comment
Answers (1)
Add AnswerI believe the right class definition is something like this.
[XmlRoot(ElementName="number")] public class Number { [XmlAttribute(AttributeName="id")] public string Id { get; set; } [XmlText] public string Text { get; set; } } [XmlRoot(ElementName="numbers")] public class Numbers { [XmlElement(ElementName="number")] public List<Number> Number { get; set; } }