I've got a problem when deserializing partially works. When I have an xml node with attributes, all the attribute values get loaded correctly into my class but when I use elements, it just returns null.
I have the following stored in an xml file:
<?xml version="1.0" encoding="ISO8859-1"?>
...
<numbers>
<number id="55">name1</number>
<number id="4">name2</number>
</numbers>
...
Class is defined as follows:
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; }
}
What keeps being null is the name.. I've tried multiple things as changing the list to arrary but whatever I do name is null.
I see the above class is wrong because when I serialize it back to XML i get the following:
<numbers>
<number id="123">
<number>abc</number>
</number>
<number id="45">
<number>abc</number>
</number>
</numbers>
Could anyone point my in the right direction?
Thanks
CodePudding user response:
I think thaht the correct class definition must be 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; }
}