[英]XmlSerializer exception when deserializing derived class (<Derived xmlns=''> was not expected)
I am trying to serialize and deserialize a hierarchy of classes using XmlSerializer. 我正在尝试使用XmlSerializer序列化和反序列化类的层次结构。 The serialization works fine, but when I try to deserialize I get this exception:
序列化工作正常,但是当我尝试反序列化时,出现此异常:
System.InvalidOperationException: There is an error in XML document (2, 2).
System.InvalidOperationException:XML文档(2、2)中存在错误。 ---> System.InvalidOperationException:
<Derived xmlns=''>
was not expected.---> System.InvalidOperationException:不需要
<Derived xmlns=''>
。
This is the xml that I am trying to deserialize: 这是我要反序列化的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>
This is the code that I am using: 这是我正在使用的代码:
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());
}
}
}
Why does the deserialization not work? 为什么反序列化不起作用? How can I get it to work?
我如何使它工作?
You're creating an XmlSerializer
which expects to deserialize just Base
objects. 您正在创建一个
XmlSerializer
, 期望仅反序列化Base
对象。 It doesn't expect to see a <Derived>
element. 它不希望看到
<Derived>
元素。 If you use 如果您使用
XmlSerializer deserializer = new XmlSerializer(typeof(Derived));
you don't get the exception. 你没有例外。 Alternatively, when you serialize the instance of
Derived
, you can use a serializer which will produce a <Base>
element: 或者,当序列化
Derived
的实例时,可以使用一个序列化程序,该序列化程序将产生一个<Base>
元素:
XmlSerializer serializer = new XmlSerializer(typeof(Base));
That will still deserialize to an instance of Derived
, because the XML will include 这仍然将反序列化为
Derived
的实例,因为XML将包括
xsi:type="Derived"
Basically your serializer and deserializer need to be constructed with the same type. 基本上,您的串行器和解串器需要使用相同的类型构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.