簡體   English   中英

如何在不事先知道類型的情況下使用XmlSerializer反序列化可能是基類或派生類的對象?

[英]How do I use an XmlSerializer to deserialize an object that might be of a base or derived class without knowing the type beforehand?

在C#中,如何使用XmlSerializer反序列化可能是基類的對象,或者在不事先知道類型的情況下反序列化任何幾個派生類?

我的所有派生類都添加了其他數據成員。 我已經制作了一個簡單的GUI,可以序列化和反序列化類對象。 它將序列化對象,因為任何繼承的類(甚至只是基類)都適合於用戶選擇填充的字段。

我對序列化沒有任何問題; 問題是反序列化。 如何在不事先知道類的情況下讓XmlSerializer將數據反序列化為正確的派生類? 我目前創建一個XmlReader來讀取XML文件的第一個節點並從中確定類,它似乎適用於我的目的,但它似乎是一個非常不優雅的解決方案。

我在下面發布了一些示例代碼。 有什么建議么?

BaseType objectOfConcern = new BaseType();
XmlSerializer xserializer;
XmlTextReader xtextreader = new XmlTextReader(DEFAULT_FILENAME);

do { xtextreader.Read(); } while (xtextreader.NodeType != XmlNodeType.Element);

string objectType = xtextreader.Name;
xtextreader.Close();

FileStream fstream = new FileStream(DEFAULT_FILENAME, FileMode.Open);

switch (objectType)
    {
case "type1":
    xserializer = new XmlSerializer(typeof(DerivedType));

    objectOfConcern = (DerivedType)xserializer.Deserialize(fstream);

    //Load fields specific to that derived type here
    whatever = (objectOfConcern as DerivedType).NoOfstreamubordinates.ToString();

    case "xxx_1":
        //code here

    case "xxx_2":
        //code here

    case "xxx_n":
        //code here

        //and so forth

    case "BaseType":
    xserializer = new XmlSerializer(typeof(BaseType));
    AssignEventHandler(xserializer);
    objectOfConcern = (BaseType)xserializer.Deserialize(fstream);
}

//Assign all deserialized values from base class common to all derived classes here

//Close the FileStream
fstream.Close();

你有一些包含派生類型的根類/標簽嗎? 如果是,您可以使用XmlElementAttribute將標記名稱映射到類型:

public class RootElementClass
{
    [XmlElement(ElementName = "Derived1", Type = typeof(Derived1BaseType))]
    [XmlElement(ElementName = "Derived2", Type = typeof(Derived2BaseType))]
    [XmlElement(ElementName = "Derived3", Type = typeof(Derived3BaseType))]
    public BaseType MyProperty { get; set; }
}

public class BaseType { }
public class Derived1BaseType : BaseType { }
public class Derived2BaseType : BaseType { }
public class Derived3BaseType : BaseType { }

我最近為基類T和T的任何派生類編寫了這個通用的serializer \\ deserializer。到目前為止似乎工作。

Type []數組存儲T和T本身的所有派生類型。 反序列化器會嘗試每一個,並在找到正確的序列時返回。

/// <summary>
/// A generic serializer\deserializer
/// </summary>
/// <typeparam name="T"></typeparam>
public static class Serializer<T>
{
    /// <summary>
    /// serialize an instance to xml
    /// </summary>
    /// <param name="instance"> instance to serialize </param>
    /// <returns> instance as xml string </returns>
    public static string Serialize(T instance)
    {
        StringBuilder sb = new StringBuilder();
        XmlWriterSettings settings = new XmlWriterSettings();

        using (XmlWriter writer = XmlWriter.Create(sb, settings))
        {
            XmlSerializer serializer = new XmlSerializer(instance.GetType());
            serializer.Serialize(writer, instance);
        }

        return sb.ToString();
    }

    /// <summary>
    /// deserialize an xml into an instance
    /// </summary>
    /// <param name="xml"> xml string </param>
    /// <returns> instance </returns>
    public static T Deserialize(string xml)
    {
        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            foreach (Type t in types)
            {
                XmlSerializer serializer = new XmlSerializer(t);
                if (serializer.CanDeserialize(reader))
                    return (T)serializer.Deserialize(reader);
            }
        }

        return default(T);
    }

    /// <summary>
    /// store all derived types of T:
    /// is used in deserialization
    /// </summary>
    private static Type[] types = AppDomain.CurrentDomain.GetAssemblies()
                                        .SelectMany(s => s.GetTypes())
                                        .Where(t => typeof(T).IsAssignableFrom(t)
                                            && t.IsClass
                                            && !t.IsGenericType)
                                            .ToArray();
}

您可以嘗試使用構造函數XmlSerializer(Type type,Type [] extraTypes)來創建一個適用於所有相關類型的序列化程序。

如果您未設置使用XmlSerializer ,則可以使用帶有KnownType屬性的DataContractSerializer

您需要做的就是為每個子類的父類添加一個KnownType屬性, DataContractSerializer將完成剩下的工作。

在序列化為xml時, DataContractSerializer將添加類型信息,並在反序列化時使用該類型信息來創建正確的類型。

例如,以下代碼:

[KnownType( typeof( C2 ) )]
[KnownType( typeof( C3 ) )]
public class C1 {public string P1 {get;set;}}
public class C2 :C1 {public string P2 {get;set;}}
public class C3 :C1 {public string P3 {get;set;}}

class Program
{
  static void Main(string[] args)
  {
    var c1 = new C1{ P1="c1"};
    var c2 = new C2{ P1="c1", P2="c2"};
    var c3 = new C3{ P1="c1", P3="c3"};

    var s = new DataContractSerializer( typeof( C1 ) );
    Test( c1, s );
    Test( c2, s );
    Test( c3, s );
  }

  static void Test( C1 objectToSerialize, DataContractSerializer serializer )
  {
    using ( var stream = new MemoryStream() )
    {
      serializer.WriteObject( stream, objectToSerialize );
      stream.WriteTo( Console.OpenStandardOutput() );
      stream.Position = 0;
      var deserialized = serializer.ReadObject( stream );
      Console.WriteLine( Environment.NewLine + "Deserialized Type: " + deserialized.GetType().FullName );              
    }
  }
}

將輸出:

<C1 xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<P1>c1</P1></C1>

Deserialized Type: ConsoleApplication1.C1

<C1 i:type="C2" xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<P1>c1</P1><P2>c2</P2></C1>

Deserialized Type: ConsoleApplication1.C2

<C1 i:type="C3" xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<P1>c1</P1><P3>c3</P3></C1>

Deserialized Type: ConsoleApplication1.C3

在輸出中,您會注意到c2和c3的xml包含額外的類型信息,這些信息允許DataContractSerializer.ReadObject創建正確的類型。

你可以使用XmlInclude

[XmlInclude(typeof(MyClass))]
public abstract class MyBaseClass
{
   //...
}

否則,如果要在序列化時添加類型:

Type[] types = new Type[]{ typeof(MyClass) }

XmlSerializer serializer = new XmlSerializer(typeof(MyBaseClass), types);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM