XML文件与实体类之间的互相转换

 

XML文件与实体类的互相转换

一.将XML文件反序列化为实体类对象

  1. 通常程序的配置信息都保存在程序或者网站的专门的配置文件中(App.config/web.config)。但是现在为了演示XML序列化和反序列化,将配置信息保存在一个XML文件(config.xml)中,通过反序列化将配置信息读取出来保存到一个单独的类(Config.cs)中。这样如果需要用到配置信息,没必要每次都读写XML文件,只需要调用Config这个类就可以获取对应节点的信息。

  config.xml:

复制代码
<?xml version="1.0" encoding="utf-8"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsAuto="true">

  <Description>定时扫描数据库,通过客户号和业务号读取客户信息</Description>

  <CustomerInfos>
    <CustomerInfo>
      <CustomerId>0013</CustomerId>
      <BusinessId>03</BusinessId>
    </CustomerInfo>
    <CustomerInfo>
      <CustomerId>0022</CustomerId>
      <BusinessId>02</BusinessId>
    </CustomerInfo>
  </CustomerInfos>

  <ScanConfigs>
    <BeginTime>22:00:00</BeginTime>
    <EndTimme>23:00:00</EndTimme>
  </ScanConfigs>

</Config>
复制代码

  2. 为了将上面这个XML转换为想要的实体类对象,方便在程序里面读取节点数据,需要创建一个相对应的实体类,在实体类中用[XmlRoot][XmlElement][XmlAttribute]等属性标识。

  Config.cs:

复制代码
  //XmlRoot表明这个类对应的是XML文件中的根节点
  [XmlRoot(ElementName="Config")]
    public class Config
    {
     //XmlElement表明这个字段对应的是XML文件中当前父节点下面的一个子节点
     //ElementName就是XML里面显示的当前节点名称
     //类中的字段名称与对应的XML节点的名称可以不同(比如在这里类Config中的属性ClientDescription对应XML文件中根节点Config下面的子节点Description)
        [XmlElement(ElementName = "Description")]
        public string ClientDescription { get; set; }

     //XmlAttribute表明这个字段是XML文件中当前节点的一个属性
        [XmlAttribute(AttributeName="IsAuto")]
        public string IsAuto { get; set; }

        [XmlElement(ElementName = "CustomerInfos")]
        public CustomerInfos CustomerInfos
        {
            get;
            set;
        }

        [XmlElement(ElementName = "ScanConfigs")]
        public ScanConfigs ScanConfigs
        {
            get;
            set;
        }
    }

    public class CustomerInfos
    {
        [XmlElement(ElementName = "CustomerInfo")]
        public CustomerInfo[] cs
        {
            get;
            set;
        }
    }

    public class CustomerInfo
    {
        [XmlElement(ElementName = "CustomerId")]
        public string CustomerId { get; set; }

        [XmlElement(ElementName = "BusinessId")]
        public string BusinessId { get; set; }
    }


    public class ScanConfigs
    {
        [XmlElement(ElementName = "BeginTime")]
        public string BeginTime { get; set; }

        [XmlElement(ElementName = "EndTimme")]
        public string EndTimme { get; set; }
    }
复制代码

  3. 下面的代码调用.net的XmlSerializer类的方法进行XML的反序列化

复制代码
  public class XmlUtil
    {
        //反序列化
     //接收2个参数:xmlFilePath(需要反序列化的XML文件的绝对路径),type(反序列化XML为哪种对象类型)
        public static object DeserializeFromXml(string xmlFilePath, Type type)
        {
            object result = null;
            if (File.Exists(xmlFilePath))
            {
                using (StreamReader reader = new StreamReader(xmlFilePath))
                {
                    XmlSerializer xs = new XmlSerializer(type);
                    result = xs.Deserialize(reader);
                }
            }
            return result;
        }
    }
复制代码

  4. 反序列化

   string xmlPath = "d:\config.xml";
    Config c = XmlUtil.DeserializeFromXml(xmlPath, typeof(Config)) as Config;

二. 序列化

  1. 反过来的,也可以将Config类的一个对象序列化为XML文件.下面的代码通过调用.net的XmlSerializer类的方法将对象序列化为XML文件

复制代码
  public class XmlUtil
    {
        //序列化
     //接收4个参数:srcObject(对象的实例),type(对象类型),xmlFilePath(序列化之后的xml文件的绝对路径),xmlRootName(xml文件中根节点名称)
     //当需要将多个对象实例序列化到同一个XML文件中的时候,xmlRootName就是所有对象共同的根节点名称,如果不指定,.net会默认给一个名称(ArrayOf+实体类名称)
        public static void SerializeToXml(object srcObject, Type type,string xmlFilePath, string xmlRootName)
        {
            if (srcObject != null && !string.IsNullOrEmpty(xmlFilePath))
            {
                type = type != null ? type : srcObject.GetType();

                using(StreamWriter sw=new StreamWriter(xmlFilePath))
                {
                    XmlSerializer xs = string.IsNullOrEmpty(xmlRootName) ?
                        new XmlSerializer(type) :
                        new XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                    xs.Serialize(sw, srcObject);
                }
            }
        }
    }
复制代码

  2. 序列化

 
       Config config = new Config();
            config.ClientDescribe = "定时扫描数据库,通过客户号和业务号读取客户信息.";
            config.IsAuto = "true";

            CustomerInfo ci1 = new CustomerInfo();
            ci1.CustomerId = "0013";
            ci1.BusinessId = "03";
            CustomerInfo ci2 = new CustomerInfo();
            ci2.CustomerId = "0022";
            ci2.BusinessId = "02";
            CustomerInfos cis = new CustomerInfos();
            cis.cs = new CustomerInfo[] { ci1, ci2 };

            config.CustomerInfos = cis;

            ScanConfigs sc = new ScanConfigs();
            sc.BeginTime = "22:00:00";
            sc.EndTimme = "23:00:00";

            config.ScanConfigs = sc;

            XmlUtil.SerializeToXml(config, config.GetType(), "d:\config.xml", null);
原文地址:https://www.cnblogs.com/smilekiss/p/4450339.html