.net 如何用XML反序列化未知类型的对象?

.net 如何用XML反序列化未知类型的对象?,.net,xml-serialization,.net,Xml Serialization,我想用XmlSerializer将对象保存到硬盘(如缓存)。在这种情况下,我没有任何问题 然而,当我想将这个XML反序列化为一个对象时,我得到了一个错误。有什么办法吗 要将XML反序列化为未知对象或我创建的对象?另一种更有效的(比DOM或SAX)数据绑定方法如下:另一种更有效的(比DOM或SAX)数据绑定方法如下:您可以使用SerializationHelper.DeSerializeNow,如我在文章中所述: 您可以使用SerializationHelper.DeSerializeNow,如

我想用
XmlSerializer
将对象保存到硬盘(如缓存)。在这种情况下,我没有任何问题

然而,当我想将这个XML反序列化为一个对象时,我得到了一个错误。有什么办法吗
要将XML反序列化为未知对象或我创建的对象?

另一种更有效的(比DOM或SAX)数据绑定方法如下:

另一种更有效的(比DOM或SAX)数据绑定方法如下:

您可以使用SerializationHelper.DeSerializeNow,如我在文章中所述:


您可以使用SerializationHelper.DeSerializeNow,如我的文章中所述:


在.Net中无法反序列化未知对象


要成功序列化/反序列化XML对象,该类必须具有默认构造函数。最好的方法是向我们显示准确的错误消息。您可以这样做吗?

在.Net中无法反序列化未知对象


要成功序列化/反序列化XML对象,该类必须具有默认构造函数。最好的方法是向我们显示准确的错误消息。可以这样做吗?

为什么不先序列化类的类型(System.Type类是可序列化的)


然后可以检查序列化的类型并创建正确的实例。

为什么不先序列化类的类型(System.type类是可序列化的)

然后,您可以检查序列化了哪种类型,并创建正确的实例。

#

这是我的解决方案:只需将字符串保存到文本文件或任何你想命名的文件中

用法如下:

var xmlString = XmlHelper.Serialize(myObject);
var myNewObject = XmlHelper.Deserialize<myObjectType>(xmlString);
var xmlString=XmlHelper.Serialize(myObject);
var myNewObject=XmlHelper.Deserialize(xmlString);
下面是课堂:

public static class XmlHelper
    {
        /// <summary>
        /// Gets the XML from an object, used like: var test = this.Serialize(response); for troubleshooting.
        /// </summary>
        /// <param name="pObject">The object.</param>
        /// <returns></returns>
        public static string Serialize(object pObject)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(pObject.GetType());
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            serializer.Serialize(sw, pObject);
            return Beautify(sb.ToString());
        }

        /// <summary>
        /// Deserializes the specified input.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static T Deserialize<T>(string input)
        where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
                return (T)ser.Deserialize(sr);
        }

        /// <summary>
        /// Beautifies the specified XML stuff.
        /// </summary>
        /// <param name="xmlStuff">The XML stuff.</param>
        /// <returns></returns>
        public static string Beautify(string xmlStuff)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xmlStuff);

            string strRetValue = null;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            // enc = new System.Text.UTF8Encoding(false);

            System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings
            {
                Encoding = enc,
                Indent = true,
                IndentChars = "    ",
                NewLineChars = "\r\n",
                NewLineHandling = System.Xml.NewLineHandling.Replace,
                //xmlWriterSettings.OmitXmlDeclaration = true;
                ConformanceLevel = System.Xml.ConformanceLevel.Document
            };


            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
                {
                    doc.Save(writer);
                    writer.Flush();
                    ms.Flush();

                    writer.Close();
                } // End Using writer

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc))
                {
                    // Extract the text from the StreamReader.
                    strRetValue = sr.ReadToEnd();

                    sr.Close();
                } // End Using sr

                ms.Close();
            } // End Using ms


            /*
            System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding
            using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings))
            {
                doc.Save(writer);
                writer.Close();
            } // End Using writer
            strRetValue = sb.ToString();
            sb.Length = 0;
            sb = null;
            */

            xmlWriterSettings = null;
            return strRetValue;
        } // End Function Beautify
    }
公共静态类XmlHelper
{
/// 
///从对象获取XML,如:var test=this.Serialize(response);用于疑难解答。
/// 
///物体。
/// 
公共静态字符串序列化(对象POObject)
{
System.Xml.Serialization.XmlSerializer serializer=new System.Xml.Serialization.XmlSerializer(pObject.GetType());
StringBuilder sb=新的StringBuilder();
StringWriter sw=新的StringWriter(sb);
序列化器。序列化(sw、POObject);
使(某人)恢复美丽;
}
/// 
///反序列化指定的输入。
/// 
/// 
///输入。
/// 
公共静态T反序列化(字符串输入)
T:在哪里上课
{
System.Xml.Serialization.XmlSerializer ser=new System.Xml.Serialization.XmlSerializer(typeof(T));
使用(StringReader sr=新StringReader(输入))
返回(T)序列反序列化(sr);
}
/// 
///美化指定的XML内容。
/// 
///XML的东西。
/// 
公共静态字符串美化(字符串xmlStuff)
{
System.Xml.XmlDocument doc=new System.Xml.XmlDocument();
doc.LoadXml(xmlStuff);
字符串stretvalue=null;
System.Text.Encoding enc=System.Text.Encoding.UTF8;
//enc=新系统.Text.UTF8Encoding(false);
System.Xml.XmlWriterSettings XmlWriterSettings=new System.Xml.XmlWriterSettings
{
编码=enc,
缩进=真,
缩进字符=”,
NewLineChars=“\r\n”,
NewLineHandling=System.Xml.NewLineHandling.Replace,
//xmlWriterSettings.OmitXmlDeclaration=true;
ConformanceLevel=System.Xml.ConformanceLevel.Document
};
使用(System.IO.MemoryStream ms=new System.IO.MemoryStream())
{
使用(System.Xml.XmlWriter writer=System.Xml.XmlWriter.Create(ms,xmlWriterSettings))
{
保存文档(编写器);
writer.Flush();
弗拉什女士();
writer.Close();
}//结束使用writer
ms.Position=0;
使用(System.IO.StreamReader sr=新的System.IO.StreamReader(ms,enc))
{
//从StreamReader中提取文本。
stretvalue=sr.ReadToEnd();
高级关闭();
}//结束使用sr
Close女士();
}//结束使用ms
/*
System.Text.StringBuilder sb=new System.Text.StringBuilder();//始终生成UTF-16,无论设置的编码是什么
使用(System.Xml.XmlWriter writer=System.Xml.XmlWriter.Create(sb,设置))
{
保存文档(编写器);
writer.Close();
}//结束使用writer
stretvalue=sb.ToString();
sb.长度=0;
sb=null;
*/
xmlWriterSettings=null;
返回strertvalue;
}//结束函数美化
}
假设C#

这是我的解决方案:只需将字符串保存到文本文件或任何你想命名的文件中

用法如下:

var xmlString = XmlHelper.Serialize(myObject);
var myNewObject = XmlHelper.Deserialize<myObjectType>(xmlString);
var xmlString=XmlHelper.Serialize(myObject);
var myNewObject=XmlHelper.Deserialize(xmlString);
下面是课堂:

public static class XmlHelper
    {
        /// <summary>
        /// Gets the XML from an object, used like: var test = this.Serialize(response); for troubleshooting.
        /// </summary>
        /// <param name="pObject">The object.</param>
        /// <returns></returns>
        public static string Serialize(object pObject)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(pObject.GetType());
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            serializer.Serialize(sw, pObject);
            return Beautify(sb.ToString());
        }

        /// <summary>
        /// Deserializes the specified input.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static T Deserialize<T>(string input)
        where T : class
        {
            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));

            using (StringReader sr = new StringReader(input))
                return (T)ser.Deserialize(sr);
        }

        /// <summary>
        /// Beautifies the specified XML stuff.
        /// </summary>
        /// <param name="xmlStuff">The XML stuff.</param>
        /// <returns></returns>
        public static string Beautify(string xmlStuff)
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xmlStuff);

            string strRetValue = null;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            // enc = new System.Text.UTF8Encoding(false);

            System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings
            {
                Encoding = enc,
                Indent = true,
                IndentChars = "    ",
                NewLineChars = "\r\n",
                NewLineHandling = System.Xml.NewLineHandling.Replace,
                //xmlWriterSettings.OmitXmlDeclaration = true;
                ConformanceLevel = System.Xml.ConformanceLevel.Document
            };


            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
                {
                    doc.Save(writer);
                    writer.Flush();
                    ms.Flush();

                    writer.Close();
                } // End Using writer

                ms.Position = 0;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc))
                {
                    // Extract the text from the StreamReader.
                    strRetValue = sr.ReadToEnd();

                    sr.Close();
                } // End Using sr

                ms.Close();
            } // End Using ms


            /*
            System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding
            using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings))
            {
                doc.Save(writer);
                writer.Close();
            } // End Using writer
            strRetValue = sb.ToString();
            sb.Length = 0;
            sb = null;
            */

            xmlWriterSettings = null;
            return strRetValue;
        } // End Function Beautify
    }
公共静态类XmlHelper
{
/// 
///从对象获取XML,如:var test=this.Serialize(response);用于疑难解答。
/// 
///物体。
/// 
公共静态字符串序列化(对象POObject)
{
System.Xml.Serialization.XmlSerializer serializer=new System.Xml.Serialization.XmlSerializer(pObject.GetType());
StringBuilder sb=新的StringBuilder();
StringWriter sw=新的StringWriter(sb);
序列化器。序列化(sw、POObject);
使(某人)恢复美丽;
}
///