我如何反序列化XML不知道类型事先? [英] How do I deserialize XML without knowing the type beforehand?

查看:135
本文介绍了我如何反序列化XML不知道类型事先?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有几个基本的对象,像这样:

Say I have a couple of basic objects like so:

[Serializable]
public class Base
{

    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

[Serializable]
public class Sub: Base
{
    public List<string> Property3 { get; set; }

    public Sub():base()
    {
        Property3 = new List<string>();
    }        
}

和序列化他们像这样:

Sub s = new Sub {Property1 = "subtest", Property2 = 1000};
s.Property3.Add("item 1");
s.Property3.Add("item 2");

XmlSerializer sFormater = new XmlSerializer(typeof(Sub));
using (FileStream fStream = new FileStream("SubData.xml", 
    FileMode.Create, FileAccess.Write, FileShare.None))
{
    sFormater.Serialize(fStream, s);
}

如何反序列化它们,让我找回了正确的类?

How can I deserialize them, so that I get back the correct class?

作为,我想是这样的。

XmlSerializer bFormater = new XmlSerializer(typeof (Base));
Base newBase;
using (FileStream fStream = new FileStream("BaseData.xml", 
    FileMode.Open, FileAccess.Read, FileShare.Read))
{
    newBase = (Base) bFormater.Deserialize(fStream);
}

除非我能传递一个XML文件,一个从基础和正确的类将被创建的任何类。

Except I'd be able to pass it an XML file for any class that descends from Base and the correct class would be created.

我想我可以读取XML的根节点的名称,并使用switch语句来创建正确的XmlSerializer的,但我想知道如果有一个更简单的方法。

I'm thinking I could read the name of the root node of the XML and use a switch statement to create the correct XmlSerializer, but I was wondering if there was a simpler way.

推荐答案

使用您的基类中的 [XmlInclude] 属性来告诉派生类的XML序列化,所以它可以计算出,以创造什么。你最后code段应然后正常工作。

Use the [XmlInclude] attribute on your base class to tell the XML serializer about derived classes, so it can figure out what to create. Your last code snippet should then work correctly.

这篇关于我如何反序列化XML不知道类型事先?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆