Summary of XmlSerializer serialization

Source: Internet
Author: User

XmlSerializer under the namespace using System.Xml.Serialization.

Serialization and deserialization of code:

usingSystem.IO;usingSystem.Xml;usingSystem.Xml.Serialization;namespaceconsoleapplication1{ Public classpublicfunction {//serializing to XmlNode         Public Static voidSerialize<t> (T T, outXmlNode node) {XmlDocument doc=NewXmlDocument (); using(MemoryStream ms =NewMemoryStream ()) {XmlSerializer Serializer=NewXmlSerializer (typeof(T),typeof(T). Assembly.getname ().                Name); Serializer.                Serialize (MS, T); Ms. Position=0; Doc.                Load (MS); Node=Doc.            LastChild; }        }        //deserializing data in a XmlNode         Public Static voidDeserialize<t> (XmlNode node, outT T) {XmlSerializer Serializer=NewXmlSerializer (typeof(T),typeof(T). Assembly.getname ().            Name); XmlNodeReader Reader=NewXmlNodeReader (node); T=(T) serializer.        Deserialize (reader); }        //serializing to a file         Public Static voidSerializefile<t> (T T,stringfilepath) {           using(XmlWriter writer =NewXmlTextWriter (filepath, Encoding.UTF8)) {XmlSerializer Serializer=NewXmlSerializer (typeof(T)); Serializer.           Serialize (writer,t); }        }        //deserializing the contents of a file         Public Static voidDeserializefile<t> (stringFilepath, outT T) {T=default(T); using(XmlReader reader =NewXmlTextReader (Filepath)) {XmlSerializer Serializer=NewXmlSerializer (typeof(T)); Serializer.            Deserialize (reader); }        }    }}

XmlSerializer serialization Rules:

1. Only public member variables can be serialized, protected, private, public static declared fields do not support serialization.

2. Object properties must be readable and writable.

3. The object must have an argument-free constructor for deserialization.

4. The sequence of serialization is consistent with the order of the field definitions.

5. When you serialize a subclass, and when you declare a base class, you need to use XmlInclude to declare the subclass type in the base class, such as the following Listccabstract field.

usingSystem.Xml;usingSystem.Xml.Serialization;usingSystem.IO;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) {Aa a=NewAa (); Publicfunction.serializefile<Aa> (A,@"D:\1.txt"); }} [XmlRoot ("Aaroot")]     Public classAa { Public Static stringStaticparam; [XmlAttribute ("Name")]         Public stringname; [XmlIgnore] Public stringIgnore; protected stringProparam; Private intAge ;  Public intPattribute {Get; Set; } [XmlArray ("List")] [XmlArrayItem ("Item")]         PublicList<ccabstract> Listccabstract {Get;Set; }  PublicAa () {Staticparam="Staticparam";  This. Name ="Aa";  This. Proparam ="Praparam";  This. Age = at; Pattribute= at; Ignore="Ignpore"; Listccabstract=Newlist<ccabstract> {NewCc ("testccabstract") }; }} [XmlInclude (typeof(Cc))] Public Abstract classccabstract {} Public classCc:ccabstract { Public stringCName;  PublicCc () {} PublicCc (stringname) {           This. Cname=name; }    }}

The serialized XML content is:

<?xml version="1.0"encoding="Utf-8"? ><aaroot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="Http://www.w3.org/2001/XMLSchema"Name="Aa"> <pAttribute> at</pAttribute> <List> <item xsi:type="Cc"> <CName>testCcAbstract</CName> </Item> </List></AaRoot>

You can see that xmlroot can specify the root node name, and name no longer acts as a xmlelement, but instead becomes a aaroot property. Fields that are identified by the XmlIgnore tag are not serialized, and fields that are declared by protected, private, public, and static do not support serialization. XmlArray can specify the name of the list type after serialization, and XmlArrayItem corresponds to the element in the list.

6. Use the XmlSerializer (Type), XmlSerializer (type,string) constructors as much as possible and cause a memory leak if other constructors are used.

For details, please see

Https://msdn.microsoft.com/zh-cn/library/system.xml.serialization.xmlserializer (vs.80). aspx

To improve performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize a specified type. The infrastructure will find and reuse these assemblies. This behavior occurs only when the following constructor is used:

System.Xml.Serialization.XmlSerializer (Type)

System.Xml.Serialization.XmlSerializer (type,string)

If you use any other constructor, multiple versions of the same assembly are generated, which are never unloaded, resulting in memory leaks and poor performance. The simplest solution is to use one of the two constructors above.

Summary of XmlSerializer serialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.