使用IXmlSerializable时未调用ReadXml

时间:2012-05-22 09:57:18

标签: c# .net xml serialization deserialization

尝试使用IXmlSerializable时遇到了一些问题。在WriteXml执行反序列化时,似乎没有调用ReadXml方法。

这是代码的精简版。

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);
}
}

要序列化和反序列化,请执行以下操作:

        //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);
        }

我刚刚在这个课程的设置上做错了吗?

2 个答案:

答案 0 :(得分:1)

我最初的印象是继承自IXmlSerializable允许我读取和写入所有传入的xml数据。但是,验证是为了确保类类型相同。因此,我需要序列化和反序列化Character

我的目的是能够序列化子类。我通过使用WriteXml方法并使用方法中的反射来获取基于根节点的关联类型。

我希望这个解释有助于其他人。

答案 1 :(得分:0)

public class UserCharacter : Character
{
    public void ReadXml(XmlReader reader)
    {
        base.ReadXml(reader);
    }
    public void WriteXml(XmlWriter writer)
    {
        base.WriteXml(writer);
    }
}