反序列化:基类型的属性

时间:2012-12-16 17:25:38

标签: c# xml-serialization xml-deserialization

我写了一个小样本来说明我得到的错误。请帮助如何反序列化。我总是假设我能够序列化我应该能够反序列化,因为我使用CLR的开箱即用功能

运行此示例时出现以下异常。

  

无法识别指定的类型:name ='Sample',namespace ='AppConsole_ChandraSandpit',在SampleBase xmlns ='AppConsole_ChandraSandpit'>

[XmlInclude(typeof(Sample))]
public class SampleBase
{
    int SampleId { get; set; }
}

public class Sample : SampleBase
{
    public int SampleId { get; set; }
}

public class SampleGroup
{
    public int GroupId
    {
        get;
        set;
    }


    public  List<SampleBase> Samples
    {
        get;
        set;
    }

    public void populate()
    {
        Samples = new List<SampleBase>();
        for (int i = 0; i <= 5; i++)
        {
            Samples.Add(new Sample());
        }
    }

    /// <summary>
    /// Hydrates the object to xml string. 
    /// </summary>
    /// <returns>serialized xml string of this object</returns>
    public  String Hydrate()
    {
        String xmlString = String.Empty;
        try
        {
            xmlString = XMLSerializationHelper.SerializeObjectToXml<SampleGroup>(this);
        }
        catch (InvalidOperationException HydrateException)
        {
            throw new InvalidOperationException(String.Format("Could not Hydrate {0} to xmlstring. Please see inner exception for details", this.GetType().ToString()), HydrateException.InnerException);
        }
        return xmlString;
    }

    /// <summary>
    /// Dehydrates the xml string to object. 
    /// </summary>
    /// <param name="xmltoDehydarte">xml string to be dehydrated to object</param>
    /// <returns>deHydrated object</returns>
    public SampleGroup Dehydrate(String xmltoDehydarte)
    {
        SampleGroup dehydratedObject = null;
        if (!String.IsNullOrEmpty(xmltoDehydarte))
        {
            try
            {
                XmlRootAttribute xRoot = new XmlRootAttribute();
                xRoot.ElementName = "SampleGroup";
                xRoot.Namespace = "AppConsole_ChandraSandpit";
                xRoot.IsNullable = true;
                dehydratedObject = XMLSerializationHelper.DeserializeXmlToObject<SampleGroup>(xmltoDehydarte, xRoot);
            }
            catch (InvalidOperationException deHydrateException)
            {
                throw new InvalidOperationException(String.Format("Could not deHydrate {0} to xmlstring. Please see inner exception for details", this.GetType().ToString()), deHydrateException.InnerException);
            }
        }
        return dehydratedObject;
    }

}

遵循序列化帮助程序的代码

public class XMLSerializationHelper : XmlSerializer
    {
 public static T DeserializeXmlToObject<T>(string xml, XmlRootAttribute xRoot)
        {
            using (MemoryStream memoryStream = new MemoryStream(StringToByteArrayUtf8(xml)))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), xRoot);
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                return (T)xmlSerializer.Deserialize(xmlTextWriter.BaseStream);
            }
        }
    public static string SerializeObjectToXml<T>(T obj)
    {
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), typeof(T).Namespace);
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        xmlSerializer.Serialize(xmlTextWriter, obj);
        memoryStream = (MemoryStream) xmlTextWriter.BaseStream;
        string xmlString = ByteArrayToStringUtf8(memoryStream.ToArray());
        xmlTextWriter.Close();
        memoryStream.Close();
        memoryStream.Dispose();
        return xmlString;
    }

}

可以在控制台中使用以下内容进行测试

internal class Program
    {
        private static void Main(string[] args)
        {

            SampleGroup SG = new SampleGroup();
            SG.populate();
            SG = SG.Dehydrate(SG.Hydrate());
            Console.WriteLine("Test Complete press a Key");
            Console.ReadKey();
}
}

0 个答案:

没有答案