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结构

<?xml version="1.0"?>
<Setting xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <PLC>
    <ComPort>1</ComPort>
  </PLC>
  <Codec>
    <ComPort>2</ComPort>
  </Codec>
  <QRcode>
    <ComPort1>3</ComPort1>
    <ComPort2>4</ComPort2>
  </QRcode>
</Setting>

我们实现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
    {
        /// <summary>
        /// XML序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public static bool SerializeXML<T>(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;
            }
        }
        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strFile"></param>
        /// <returns></returns>
        public static T DeserializeXML<T>(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<SettingXML>(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<SettingXML>(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文件中将数据读取出来。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值