[英]ReadXml not being called when using IXmlSerializable
I've had a few issue when trying to use IXmlSerializable. 尝试使用IXmlSerializable时遇到了一些问题。 The ReadXml method does not seem to get called when deserializing while the the WriteXml does. 反序列化时似乎不会调用ReadXml方法,而WriteXml却会被调用。
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. 最初给我的印象是,从IXmlSerializable继承后,我可以读写所有传入的xml数据。 However validation is done to ensure that the class types are the same. 但是,会进行验证以确保类类型相同。 Therefore I would have needed to serialise and deserialise Character
. 因此,我将需要对Character
进行序列化和反序列化。
My intention was to be able to serialise child classes. 我的意图是能够序列化子类。 I've managed this by using the WriteXml
method and using reflection within the method to get the associated type based on the root node. 我已经通过使用WriteXml
方法并在方法中使用反射来基于根节点获取关联的类型来进行管理。
I hope this explanation helps someone else. 我希望这种解释对其他人有帮助。
public class UserCharacter : Character
{
public void ReadXml(XmlReader reader)
{
base.ReadXml(reader);
}
public void WriteXml(XmlWriter writer)
{
base.WriteXml(writer);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.