可以使用XmlSerializer的时候使用抽象类的XML序列化? [英] Is possible to use abstract class in xml serialization when using XmlSerializer?
问题描述
问题
当我使用 System.Xml.Serialization.XmlSerializer
饰有类的System.Xml.Serialization
属性(例如, XmlRoot
,的XmlElement
,...),我可以创建一些类的属性与类型作为抽象类?
Question
When I'm using System.Xml.Serialization.XmlSerializer
with classes decorated with the System.Xml.Serialization
attributes (e.g. XmlRoot
, XmlElement
, ...) can I create a property in some of the classes with type as a abstract class?
场景
我有这些类:
Scenario
I have these classes:
[XmlRoot("autor")]
public class Author
{
[XmlElement("name")]
public string Name { get; set; }
[XmlArray("books")]
[XmlArrayItem("book")]
public List<Book> Livros { get; set; }
[XmlElement("info")]
public ExtraData ExtraData { get; set; }
}
public class Book
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("year")]
public int Year { get; set; }
}
public abstract class ExtraData
{
}
public class ExtraDataTest : ExtraData
{
[XmlElement("test")]
public string Test { get; set; }
}
和我试试这个片断:
var author = new Author
{
Name = "George R. R. Martin",
Livros = new List<Book>
{
new Book { Name = "A Game of Thrones", Year = 1996 },
new Book { Name = "The Hedge Knight", Year = 1998 },
},
// ExtraData = new ExtraDataTest { Test = "Some Info" }
// See the comment below to know why this line was commented.
};
var serializer = new XmlSerializer(typeof(Author));
using(var ms = new MemoryStream())
using(var sw = new StreamWriter(ms))
using(var sr = new StreamReader(ms))
{
var ns = new XmlSerializerNamespaces();
ns.Add("","");
serializer.Serialize(sw, author, ns);
sw.Flush();
ms.Position = 0;
sr.ReadToEnd().Dump(); // Dump is a extended method of LinqPad
}
结果是:
<?xml version="1.0" encoding="utf-8"?>
<autor>
<name>George R. R. Martin</name>
<books>
<book>
<name>A Game of Thrones</name>
<year>1996</year>
</book>
<book>
<name>The Hedge Knight</name>
<year>1998</year>
</book>
</books>
</autor>
问题
所以,如果我取消对设置而额外
属性唯一的例外是抛出当我试图序列化对象的行:
Problem
So if I uncomment the line that set the ExtraData
property one exception is throw when I try to serialize the object:
System.ObjectDisposedException
无法访问已关闭的流。
System.ObjectDisposedException
Cannot access a closed Stream.
所以这就是为什么我要问,如果有可能,如果是的话,怎么办?
So this is why I'm asking if it possible, if yes, how?
推荐答案
这是可能的。
唯一缺少的,我从你的code看到的是使用<一个href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlincludeattribute%28v=vs.110%29.aspx"相对=nofollow> XmlInclude attrubute 你的抽象类通知,它应该寻找派生类像这样的串行器:
The only thing missing that I see from your code is to use the XmlInclude attrubute on your abstract class to inform the serializer that it should look for derived classes like this:
[XmlInclude(typeof(ExtraDataTest))]
public abstract class ExtraData
{
}
这篇关于可以使用XmlSerializer的时候使用抽象类的XML序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!