问题描述
尝试使用的IXmlSerializable时,我也曾有过一些问题。 ReadXml方法似乎并不反序列化,而在做中WriteXML时被调用。
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.
下面是的code一个简化版本。
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);
}
}
要连载和deserialise我做到以下几点:
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?
推荐答案
我本来是在IM pression从IXmlSerializable的继承让我读写所有传入的XML数据的能力。然而验证做是为了确保在类类型是相同的。因此,我会需要序列化和deserialise 字符
。
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
.
我的目的是要能够序列化的子类。我已经使用中WriteXML
方法和使用方法中反射来获取基于根节点相关类型管理这一点。
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.
我希望这个解释可以帮助别人。
I hope this explanation helps someone else.
这篇关于使用时的IXmlSerializable的ReadXml不会被调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!