日期:2014-05-18  浏览次数:20916 次

求一段C#XmlSerializer的对象序列化/反序列化的源码例子。看有序列化和反序列化。
如题。

源码越完整越好。

快,准,狠者先得分。

其它废话别发上来。

------解决方案--------------------
实现序列化接口后,需要你提供2个方法


说白了就是把对象用字符串表示出来.而反序列话要能够还原



比如:如果你的对象有3个属性
class My
{
public string name;
public string age;
public string sex;

public My(string n,string a,string s)
{
name=n;
age=a;
sex=s;
}
}

他的序列话方法可以写成:
--> string.format("{0}|{1}|{2}",name,age,sex);

与之对应的,反序列话写成
string[] info = "???|???|???".split('|');
--> new My(info[0],info[1],info[2])


----------
示意一下
------解决方案--------------------
序列化:
if (Templates != null)
{
String strFileName = System.Environment.CurrentDirectory + "\\Config\\Templates.XML";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Template>));
try
{
FileStream fs = new FileStream(strFileName, FileMode.Create);
xmlSerializer.Serialize(fs, Templates);
fs.Close();
}
catch (Exception ex)
{
ErrorMsg = "DataFile Error (" + strFileName + "):" + ex.Message + ".\n" + "Please check your Xml file.";
}
}

反序列化:
String strFileName = System.Environment.CurrentDirectory + "\\Config\\Templates.XML";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Template>));
try
{
FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate);
Templates = (List<Template>)(xmlSerializer.Deserialize(fs));
fs.Close();
}
catch (Exception ex)
{
ErrorMsg = "DataFile Error (" + strFileName + "):" + ex.Message + ".\n" + "Please check your Xml file.";
}
------解决方案--------------------
C# code

#region 序列化和反序列化
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="collect"></param>
        public void Serialize( object obj ) {
            string path = Application.StartupPath + "\\Data.db";
            if( File.Exists( path ) )
                File.Delete( path );
            FileStream fs = new FileStream( path, FileMode.Create );
            BinaryFormatter formatter = new BinaryFormatter();
            try {
                formatter.Serialize( fs, obj );
            } catch( SerializationException exp ) {
                throw exp;
            } finally {
                fs.Close();
            }
        }

        /*
         * SoapFormatter
         * XmlSerializer
         * BinaryFormatter
         */

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <returns></returns>
        public object Deserialize( ) {
            string path = Application.StartupPath + "\\Data.db";
            if( !File.Exists( path ) )
                return null;
            FileStream fs = new FileStream( path, FileMode.Open );
            BinaryFormatter formatter = new BinaryFormatter();
            try {
                return (object)formatter.Deserialize( fs );
            } catch( SerializationException exp ) {
                throw exp;
            } finally {
                fs.Close();
            }
        }
        #endregion

------解决方案--------------------