Sample code analysis for Xml serialization and deserialization of XmlSerializer objects

Source: Internet
Author: User
The. Net namespace corresponding to this article is System. Xml. Serialization. the sample code in this article needs to reference this namespace. The. Net namespace corresponding to this article is System. Xml. Serialization. the sample code in this article needs to reference this namespace.

Why serialization and deserialization?

.. Net program execution, the objects reside in the memory; if the objects in the memory need to be passed to other systems for use; or you need to save it when shutting down so that the next time you start the program, you need to serialize and deserialize it.

Range:This article only Introduces xml Serialization. In fact, serialization can be binary serialization or serialization in other formats.

Look at the simplest Xml serialization code.

Class Program {static void Main (string [] args) {int I = 10; // declare the Xml serialization object instance serializer XmlSerializer serializer = new XmlSerializer (typeof (int )); // execute serialization and output the serialization result to the console serializer. serialize (Console. out, I); Console. read ();}}

The code above serializes int I and outputs the serialized result to the console. the output result is as follows:

 
 
  10
 

The serialized xml can be deserialized as follows:

Static void Main (string [] args) {using (StringReader rdr = new StringReader (@"
 
 
  
10
 ") {// Declare the serialization object instance serializer XmlSerializer serializer = new XmlSerializer (typeof (int); // deserialization, and assign the deserialization result value to the variable I int I = (int) serializer. deserialize (rdr); // output the deserialization result Console. writeLine ("I =" + I); Console. read ();}}

The code above illustrates the process of xml serialization and deserialization in the simplest way. the. Net system Class Library has done a lot of work for us, and serialization and deserialization are both very simple. However, in reality, business needs are often complicated, and it is impossible to simply serialize an int variable. in the display, we need to control the serialization of complex types.

Xml serialization of custom objects:

The System. Xml. Serialization namespace has a series of feature classes used to control the control of complex type Serialization. For example, XmlElementAttribute, XmlAttributeAttribute, XmlArrayAttribute, XmlArrayItemAttribute, and XmlRootAttribute.

Let's look at a small example. a custom Cat class has three attributes: Color, Saying, and Speed.

Namespace UseXmlSerialization {class Program {static void Main (string [] args) {// declare a Cat object 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 "}; // serialize this object XmlSerializer serializer = new XmlSerializer (typeof (Cat); // serialize the object to the console serializer. serialize (Console. out, c); Console. read () ;}} [XmlRoot ("cat")] public class Cat {// define the serialization of the Color attribute to the attributes of the cat node [XmlAttribute ("color")] public string Color {get; set;} // The Speed attribute [XmlIgnore] public int Speed {get; set;} is not serialized ;} // serialize the Saying attribute to the Xml sub-element [XmlElement ("saying")] public string Saying {get; set ;}}}

You can use XmlElement to specify the attribute to be serialized as a subnode (it is serialized as a subnode by default), or use XmlAttribute to specify the attribute to be serialized as an Xml node; you can also use the XmlIgnore feature to modify attributes without serialization.


Xml serialization of object arrays:

XmlArrayAttribute and XmlArrayItemAttribute must be used for Xml serialization of arrays. XmlArrayAttribute specifies the Xml node name of the array element and XmlArrayItemAttribute specifies the Xml node name of the array element.

Example code:

/* Yukai Technical Blog # */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) {// declare a Cat object 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 }}; // serialize the object XmlSerializer serializer = new XmlSerializer (typeof (CatCollection); // serialize and output the object to the console 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 {// define the serialization of the Color attribute to the attributes of the cat node [XmlAttribute ("color")] public string Color {get; set ;} // do not serialize the Speed attribute [XmlIgnore] public int Speed {get; set;} // set the Saying attribute to be serialized as an Xml sub-element [XmlElement ("saying")] public string Saying {get; set ;}}}

The above code will be output:

 
   
      
         
    
     White or black,  so long as the cat can catch mice,  it is a goodcat
        
       
         
    
     White or black,  so long as the cat can catch mice,  it is a goodcat
        
     
  
 

XmlSerializer memory leakage:

Thanks to chenlulouis for taking a closer look at msdn and there is indeed a leak. the msdn description is as follows:

Dynamically generated Assembly

To improve performance, the XML serialization infrastructure dynamically generates an assembly to serialize and deserialize specified types. This infrastructure will find and reuse these sets. This behavior only occurs when the following constructor is used:

XmlSerializer (Type)
XmlSerializer. XmlSerializer (Type, String)

If you use any other constructor, multiple versions of the same assembly will be generated and will never be uninstalled, which will cause memory leakage and performance degradation. The simplest solution is to use one of the two constructors mentioned earlier. Otherwise, the assembly must be cached in Hashtable, as shown in the following example.

That is to say, when using XmlSerializer for serialization, it is best to use the following two constructors when initializing the XmlSerializer object; otherwise, memory leakage will occur.
XmlSerializer (Type)
XmlSerializer. XmlSerializer (Type, String)



  

The above is the detailed content of the sample code analysis for Xml serialization and deserialization of the XmlSerializer object. For more information, see other related articles in the first PHP community!

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.