当前位置: 移动技术网 > IT编程>开发语言>.net > 深入分析XmlSerializer对象的Xml序列化与反序列化的示例详解

深入分析XmlSerializer对象的Xml序列化与反序列化的示例详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

月亮金字塔,3dmax吊灯模型,池州翠微亭

这篇随笔对应的.net命名空间是system.xml.serialization;文中的示例代码需要引用这个命名空间。
为什么要做序列化和反序列化?
.net程序执行时,对象都驻留在内存中;内存中的对象如果需要传递给其他系统使用;或者在关机时需要保存下来以便下次再次启动程序使用就需要序列化和反序列化。
范围:本文只介绍xml序列化,其实序列化可以是二进制的序列化,也可以是其他格式的序列化。
看一段最简单的xml序列化代码
复制代码 代码如下:

class program
{
    static void main(string[] args)
    {
        int i = 10;
        //声明xml序列化对象实例serializer
        xmlserializer serializer = new xmlserializer(typeof(int));
        //执行序列化并将序列化结果输出到控制台
        serializer.serialize(console.out, i);
        console.read();
    }
}

上面代码对int i进行了序列化,并将序列化的结果输出到了控制台,输出结果如下
复制代码 代码如下:

<?xml version="1.0" encoding="gb2312"?>
<int>10</int>

可以将上述序列化的xml进行反序列化,如下代码
复制代码 代码如下:

static void main(string[] args)
{
    using (stringreader rdr = new stringreader(@"<?xml version=""1.0"" encoding=""gb2312""?>
<int>10</int>"))
    {
        //声明序列化对象实例serializer
        xmlserializer serializer = new xmlserializer(typeof(int));
        //反序列化,并将反序列化结果值赋给变量i
        int i = (int)serializer.deserialize(rdr);
        //输出反序列化结果
        console.writeline("i = " + i);
        console.read();
    }
}

以上代码用最简单的方式说明了xml序列化和反序列化的过程,.net系统类库为我们做了大量的工作,序列化和反序列化都非常简单。但是在现实中业务需求往往比较复杂,不可能只简单的序列化一个int变量,显示中我们需要对复杂类型进行可控制的序列化。
自定义对象的xml序列化:
system.xml.serialization命名空间中有一系列的特性类,用来控制复杂类型序列化的控制。例如xmlelementattribute、xmlattributeattribute、xmlarrayattribute、xmlarrayitemattribute、xmlrootattribute等等。
看一个小例子,有一个自定义类cat,cat类有三个属性分别为color,saying,speed。
复制代码 代码如下:

namespace usexmlserialization
{
    class program
    {
        static void main(string[] args)
        {
            //声明一个猫咪对象
            var c = new cat { color = "white", speed = 10, saying = "white or black,  so long as the cat can catch mice,  it is a good cat" };

            //序列化这个对象
            xmlserializer serializer = new xmlserializer(typeof(cat));

            //将对象序列化输出到控制台
            serializer.serialize(console.out, c);

            console.read();
        }
    }
    [xmlroot("cat")]
    public class cat
    {
        //定义color属性的序列化为cat节点的属性
        [xmlattribute("color")]
        public string color { get; set; }

        //要求不序列化speed属性
        [xmlignore]
        public int speed { get; set; }

        //设置saying属性序列化为xml子元素
        [xmlelement("saying")]
        public string saying { get; set; }
    }
}

可以使用xmlelement指定属性序列化为子节点(默认情况会序列化为子节点);或者使用xmlattribute特性制定属性序列化为xml节点的属性;还可以通过xmlignore特性修饰要求序列化程序不序列化修饰属性。
对象数组的xml序列化:
数组的xml序列化需要使用xmlarrayattribute和xmlarrayitemattribute;xmlarrayattribute指定数组元素的xml节点名,xmlarrayitemattribute指定数组元素的xml节点名。
如下代码示例:
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.xml.serialization;

namespace usexmlserialization
{
    class program
    {
        static void main(string[] args)
        {
            //声明一个猫咪对象
            var cwhite = new cat { color = "white", speed = 10, saying = "white or black,  so long as the cat can catch mice,  it is a good cat" };
            var cblack = new cat { color = "black", speed = 10, saying = "white or black,  so long as the cat can catch mice,  it is a good cat" };

            catcollection cc = new catcollection { cats = new cat[] { cwhite,cblack} };

            //序列化这个对象
            xmlserializer serializer = new xmlserializer(typeof(catcollection));

            //将对象序列化输出到控制台
            serializer.serialize(console.out, cc);

            console.read();
        }
    }
    [xmlroot("cats")]
    public class catcollection
    {
        [xmlarray("items"),xmlarrayitem("item")]
        public cat[] cats { get; set; }
    }

    [xmlroot("cat")]
    public class cat
    {
        //定义color属性的序列化为cat节点的属性
        [xmlattribute("color")]
        public string color { get; set; }

        //要求不序列化speed属性
        [xmlignore]
        public int speed { get; set; }

        //设置saying属性序列化为xml子元素
        [xmlelement("saying")]
        public string saying { get; set; }
    }
}

以上代码将输出:
复制代码 代码如下:

<?xml version="1.0" encoding="gb2312"?>
<cats xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:xsd="http://ww
w.w3.org/2001/xmlschema">
  <items>
    <item color="white">
      <saying>white or black,  so long as the cat can catch mice,  it is a good
cat</saying>
    </item>
    <item color="black">
      <saying>white or black,  so long as the cat can catch mice,  it is a good
cat</saying>
    </item>
  </items>
</cats>

xmlserializer内存泄漏问题:
仔细看了下msdn,确实存在泄漏的情况,msdn说明如下:
动态生成的程序集
为了提高性能,xml 序列化基础结构将动态生成程序集,以序列化和反序列化指定类型。此基础结构将查找并重复使用这些程序集。此行为仅在使用以下构造函数时发生:
xmlserializer(type)
xmlserializer.xmlserializer(type, string)
如果使用任何其他构造函数,则会生成同一程序集的多个版本,且绝不会被卸载,这将导致内存泄漏和性能降低。最简单的解决方案是使用先前提到的两个构造函数的其中一个。否则,必须在 hashtable 中缓存程序集,如以下示例中所示。
也就是说我们在使用xmlserializer序列化,初始化xmlserializer对象时最好使用下面两个构造函数否则会引起内存泄漏。
xmlserializer(type)
xmlserializer.xmlserializer(type, string)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网