序列化与反序列化

Xml的序列化与反序列化在开发过程中会经常遇见到,所以为了更好的理解它,将会写几个实例

一、Deserialize()

实例一:将XML中的数据转换成实体类,将使用到XmlSerializer类的Deserialize()方法

Model:KSBMCONFIG.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Serialization;

 

namespace Model

{

    public class KSBMCONFIG

    {

        public string ConnectString { get; set; }

 

        public string ServerPath { get; set; }

 

        public string SMTPServer { get; set; }

 

        public AA AA { get; set; }

    }

    public class AA

    {

        public string BB { get; set; }

    }

}

 

 

Model的文件名是可以更改的,但在这里最好不好改动类名。

XML:

<?xml version="1.0" encoding="utf-8"?>

<KSBMCONFIG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <ConnectString>ConnectString</ConnectString>

  <ServerPath>ServerPath</ServerPath>

  <SMTPServer>SMTPServer</SMTPServer>

  <AA>

    <BB>bbbbb</BB>

  </AA>

</KSBMCONFIG>

 

 

 

结合上面XML和实体类我们可以发现,实体类中的每个字段都是与XML节点相对应的,结下来我们将Main程序中的调用

应用程序中的Main()

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Xml.Serialization;

using System.IO;

using Model;

 

namespace FrameworkApplication

{

    class Program

    {

        static void Main(string[] args)

        {

            KSBMCONFIG ks = MyOperation<KSBMCONFIG>.LoadFromXml("Xml/Xml_Serializer.xml");

           

            Console.ReadLine();

        }

    }

 

    public class MyOperation<T> where T:new()

    {

        public static T LoadFromXml(string fileName)

        {

            T kc = new T();

            FileStream  fs= null;

            using (fs = new FileStream(fileName, FileMode.Open))

            {

                XmlSerializer xmlser = new XmlSerializer(typeof(T));

                kc = (T)xmlser.Deserialize(fs);

            }

            return kc;

        }

    }

}

 

在这里我们为了LoadFromXml能适应不同类型,这里我们使用泛型处理,经运行后我们得到结果如下:

 

 

这是一个简单的实例,只要字段与XML一一对应就好了,接下来我们再讲另一种实例

不过在这里我们应该注意一点就是:在程序中我们用的是Xml的相对路径,一般情况下使用相对路径程序是会报错的,我们只需做如下处理再生成一下项目就可以了。

 

系统默认创建 的XML文件“Custom Tool”属性值是“Do not copy”不拷贝,但是我们只需要将值设为“Copy always”生成程序,这时我们就可以在程序中使用相对路径了。

如果现在XML不是像上面那样了,而是下面这种形式,用上面那种方式就不可行了

实例二、XML文件内容:

<?xml version="1.0" encoding="utf-8" ?>

<NewEggs>

  <NewEgg id="1">

    <ConnectionString>ConnectionString1</ConnectionString>

  </NewEgg>

  <NewEgg id="2">

    <ConnectionString>ConnectionString2</ConnectionString>

  </NewEgg>

  <NewEgg id="3">

    <ConnectionString>ConnectionString3</ConnectionString>

  </NewEgg>

</NewEggs>

 

 

Model文件内容:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml.Serialization;

 

namespace Model

{

    [Serializable]

    [XmlRoot("NewEggs")]

    public class NewEggs

    {

        [XmlElement("NewEgg")]

        public List<NewEgg> newNgg { get; set; }

    }

    [Serializable]

    public class NewEgg

    {

        [XmlAttribute("id")]

        public int id { get; set; }

        [XmlElement("ConnectionString")]

        public string ConnectionString { get; set; }

    }

}

 

 

这时Main方法里只需要这样写

static void Main(string[] args)

        {

           

            NewEggs NE = MyOperation<NewEggs>.LoadFromXml("Xml/XmlOne.xml");

            Console.ReadLine();

        }

 

 

 

LoadFromXml该方法还是延用上面这个类MyOperation<T>. LoadFromXml的方法

 

结果如下:

 

1    是我们得到的三个根节点下的子结点

2    是第三个子结点下的子结点和属性的值

 

 

二、Serialize()

在MyOperation<T>类下新增SaveToXml方法

      

 public static bool SaveToXml(string fileName, T t)

        {  

            XmlSerializer xmlser = new XmlSerializer(typeof(T));

            bool isSaved = false;

            using (StreamWriter sw = new StreamWriter(fileName))

            {

                try

                {

                    xmlser.Serialize(sw, t);

                    isSaved = true;

                }

                catch

                {

                }

                finally

                {

                    sw.Close();

                }

            }

            return isSaved;

        }

 

 

Main()方法中调用如下:

NewEggs NE = MyOperation<NewEggs>.LoadFromXml("Xml/XmlOne.xml");

bool bl = MyOperation<NewEggs>.SaveToXml("Xml/XmlTwo.xml", NE);

Console.ReadLine();

 

 

 

我们先从XmlOne.xml中获取实体类数据,然后再写到另一个Xml中,即XmlTwo.xml

结果:

该文件里的内容与XmlOne.xml文件中的内容一样。

 

posted on 2013-06-24 09:53  锋芒利刃  阅读(180)  评论(0)    收藏  举报

导航