C# XML一一序列化与反序列化

XML序列化:使用XmlSerializer将公共数据存储为XML的过程

XmlSerializer xs = new XmlSerializer(obj.GetType());
xs.Serialize(fs, obj); //Serialize输出可以是Stream,TextWriter或XmlWriter实例

XML反序列化:将XML实例转换回数据对象

XmlSerializer xs = new XmlSerializer(typeof(T));
T obj = (T)xs.Deserialize(fs);

实例运行:

比如我们想实现如下的XML结构



  
    1
  
  
    2
  
  
    3
    4
  

我们实现XML序列化与反序列化

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace DX_Utility
{
    public class SerializeHandle
    {
        /// 
        /// XML序列化
        /// 
        /// 
        /// 
        /// 
        /// 
        public static bool SerializeXML(T obj, string strFile)
        {
            try
            {
                using (FileStream fs = new FileStream(strFile, FileMode.Create))
                {
                    XmlSerializer xs = new XmlSerializer(obj.GetType());
                    xs.Serialize(fs, obj);
                }
                return true;
            }
            catch(System.Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return false;
            }
        }
        /// 
        /// XML反序列化
        /// 
        /// 
        /// 
        /// 
        public static T DeserializeXML(string strFile)
        {
            try
            {
                if (!File.Exists(strFile))
                {
                    return default(T);
                }
                using (FileStream fs = new FileStream(strFile, FileMode.Open))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    T obj = (T)xs.Deserialize(fs);
                    return obj;
                }
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return default(T);
            }
        }
    }
}

串行化对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace DX_Gadgets.Device
{
    [Serializable]
    [XmlRoot(ElementName = "Setting")]
    public class SettingXML
    {
        public SettingXML()
        {
            Reset();
        }

        [XmlElement(ElementName = "PLC")]
        public SettingPLC settingPLC;

        [XmlElement(ElementName = "Codec")]
        public SettingCodec settingCodec;

        [XmlElement(ElementName = "QRcode")]
        public SettingQRcode settingQRcode;

        public void Reset()
        {
            settingPLC = new SettingPLC();
            settingPLC.m_comPort = "1";

            settingCodec = new SettingCodec();
            settingCodec.m_comPort = "2";

            settingQRcode = new SettingQRcode();
            settingQRcode.m_comPort1 = "3";
            settingQRcode.m_comPort2 = "4";
        }
    }
    public class SettingPLC
    {
        [XmlElement(ElementName = "ComPort")]
        public string m_comPort;
    }
    public class SettingCodec
    {
        [XmlElement(ElementName = "ComPort")]
        public string m_comPort;
    }
    public class SettingQRcode
    {
        [XmlElement(ElementName = "ComPort1")]
        public string m_comPort1;

        [XmlElement(ElementName = "ComPort2")]
        public string m_comPort2;
    }  
}

生成文件进行调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DX_Gadgets.Device
{
    public class SettingSerialize
    {
        public SettingSerialize()
        {
            m_strSettingPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "\\GadgetsConfig";
            m_strSettingXML = m_strSettingPath + "\\Setting.xml";
        }

        public void CreateFolder()
        {
            try
            {
                //创建文件夹 C:\Users\Public\Documents\GadgetsConfig
                if (!System.IO.Directory.Exists(m_strSettingPath))
                {
                    System.IO.Directory.CreateDirectory(m_strSettingPath);
                }
            }
            catch
            {

            }
        }

        public bool Serialize_xml(SettingXML obj)
        {
            try
            {
                CreateFolder();
                DX_Utility.SerializeHandle.SerializeXML(obj, m_strSettingXML);
            }
            catch (Exception ex)
            {
                string str = string.Format("exception:{0}", ex.ToString());
                return false;
            }
            return true;
        }

        public bool Deserialize_xml(out SettingXML obj)
        {
            obj = null;

            try
            {
                //创建文件夹 C:\Users\Public\Documents\GadgetsConfig
                CreateFolder();

                obj = DX_Utility.SerializeHandle.DeserializeXML(m_strSettingXML);

            }
            catch (Exception ex)
            {
                string str = string.Format("exception:{0}", ex.ToString());
            }

            try
            {
                if (obj == null)
                {

                }
            }
            catch (Exception ex)
            {
                string str = string.Format("exception:{0}", ex.ToString());
            }
            finally
            {
                if (obj == null)
                {
                    obj = new SettingXML();
                    obj.Reset();
                    Serialize_xml(obj);
                }
            }

            return true;
        }

        private string m_strSettingXML;
        private string m_strSettingPath;
    }
}

测试:

//串行化,生成对应的XML文件
UserGlobal.m_settingSer.Serialize_xml(UserGlobal.m_settingXML);
//反串行化,从XML中获取数据
UserGlobal.m_settingSer.Deserialize_xml(out UserGlobal.m_settingXML);

这样,我们就可以通过串行化将数据写入的配置文件Setting.xml中,同时,也可以通过反串行化从Setting.xml文件中将数据读取出来。

你可能感兴趣的:(C#,XML)