反序列化派生类时的XmlSerializer异常(不期望<derived xmlns =“”>)

时间:2015-09-03 06:06:32

标签: c# serialization xml-serialization

我正在尝试使用XmlSerializer序列化和反序列化类的层次结构。序列化工作正常,但是当我尝试反序列化时,我得到了这个例外:

  

System.InvalidOperationException:XML文档中存在错误(2,2)。 ---&GT; System.InvalidOperationException:不期望<Derived xmlns=''>

这是我尝试反序列化的xml:

<?xml version="1.0"?>
<Derived xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BaseStr>Base</BaseStr>
  <DerivedStr>Derived</DerivedStr>
</Derived>

这是我正在使用的代码:

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

[XmlInclude(typeof(Derived))]
public abstract class Base 
{
    public string BaseStr { get; set; }
}

public class Derived : Base
{
    public string DerivedStr { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Derived));
            MemoryStream ms = new MemoryStream();
            serializer.Serialize(ms, new Derived() { DerivedStr = "Derived", BaseStr = "Base" });

            Console.WriteLine(Encoding.ASCII.GetChars(ms.ToArray()));

            ms.Position = 0;

            XmlSerializer deserializer = new XmlSerializer(typeof(Base));
            Base b = (Base)deserializer.Deserialize(ms);
            Console.WriteLine(b.GetType().Name);
        }
        catch(Exception ex)
        {
            Console.WriteLine();
            Console.WriteLine(ex.ToString());
        }
    }
}

为什么反序列化不起作用?我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:3)

您正在创建XmlSerializer 期望仅对Base个对象进行反序列化。它不期望看到<Derived>元素。如果你使用

XmlSerializer deserializer = new XmlSerializer(typeof(Derived));

你没有得到例外。或者,当您序列化 Derived的实例时,您可以使用将生成<Base>元素的序列化程序:

XmlSerializer serializer = new XmlSerializer(typeof(Base));

这仍将反序列化为Derived的实例,因为XML将包含

xsi:type="Derived"

基本上,您的序列化器和反序列化器需要使用相同的类型构建。