I am trying to serialize/deserialize the following XML code structure:
<Person>
<Name/>
<Age/>
<Address>
<BuildingNumber/>
<Street/>
<Town/>
<PostCode/>
</Address>
</Person>
using the classes
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public Address Address { get; set; }
}
public class Address {
public string BuildingNumber { get; set; }
public string Street { get; set; }
public string Town { get; set; }
public string PostCode { get; set; }
}
I am implemeting IXmlSerializable on both classes (it’s over-engineered for this specific example, I know, but it is required for a project I am working on which is rather more complicated!), for which serialisation works fine, but deserialisation does not.
The problem arises in the Person.ReadXml() method, which I have written as:
public void ReadXml(XmlReader reader) {
reader.ReadStartElement();
if (!reader.IsEmptyElement) {
Name = reader.ReadElementContentAsString("Name", string.Empty);
Age = reader.ReadElementContentAsInt("Age", string.Empty);
Address = (Address)reader.ReadElementContentAs(typeof(Address), null, "Address", string.Empty);
// Also failed: Address = (Address)reader.ReadElementContentAsObject("Address", string.Empty);
}
reader.ReadEndElement();
}
The final line where Address is being initialised is throwing an exception:
ReadElementContentAs() methods cannot be called on an element that has child elements. (XmlException)
Basically, how would I handle elements with child elements using IXmlSerializable?
I think you can simply use
XmlSerializerhere:Serialization is also very simple:
If you will need to customize xml (not your current case), then just use xml serialization attributes.