I’ve had a few issue when trying to use IXmlSerializable. The ReadXml method does not seem to get called when deserializing while the the WriteXml does.
Here’s a slimmed down version of the code.
public interface ICharacter {
string FullName { get; set; }
}
public class Character : ICharacter, IXmlSerializable {
public string FullName { get; set; }
public Character() {
//apply default character information
FullName = string.Empty;
}
}
public void ReadXml(XmlReader reader) {
if (reader == null) return;
//just using null to see if it's called, i've used a break point to check if it was fired
}
public void WriteXml(XmlWriter writer) {
writer.WriteElementString("FullName", FullName);
}
}
To serialise and deserialise I do the following:
//serialise example
Character character = new Character();
using (StringWriter stringWriter = new StringWriter()) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Character));
xmlSerializer.Serialize(stringWriter, character);
xml = stringWriter.ToString();
}
//deserialise example
using (StringReader stringReader = new StringReader(xml)) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UserCharacter));
_character = (Character)xmlSerializer.Deserialize(stringReader);
}
Am I just doing something wrong with the setup of this class?
I was originally under the impression that inheriting from IXmlSerializable allowed me the ability to read and write all incoming xml data. However validation is done to ensure that the class types are the same. Therefore I would have needed to serialise and deserialise
Character.My intention was to be able to serialise child classes. I’ve managed this by using the
WriteXmlmethod and using reflection within the method to get the associated type based on the root node.I hope this explanation helps someone else.