Xml serialization and deserialization of 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.

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.
Scope: 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 serializer of the Xml serialization object instance
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: <? Xml version = "1.0" encoding = "gb2312"?>
<Int> 10 </int>

The preceding serialized xml can be deserialized. The following code is static void Main (string [] args)
{
Using (StringReader rdr = new StringReader (@ "<? Xml version = "" 1.0 "" encoding = "" gb2312 ""?>
<Int> 10 </int> "))
{
// Declare the serialization object instance serializer
XmlSerializer serializer = new XmlSerializer (typeof (int ));
// Deserialization, and assign the deserialization result value to variable I
Int I = (int) serializer. Deserialize (rdr );
// Output deserialization results
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 as the attributes of the cat Node
[XmlAttribute ("color")]
Public string Color {get; set ;}
 
// The Speed attribute is not serialized.
[XmlIgnore]
Public int Speed {get; set ;}
 
// Serialize the Saying attribute to an 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.
The following code example:/* yukai technology blog http://www.cnblogs.com/yukaizhao */
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 this object
XmlSerializer serializer = new XmlSerializer (typeof (CatCollection ));
 
// Serialize 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 as the attributes of the cat Node
[XmlAttribute ("color")]
Public string Color {get; set ;}
 
// The Speed attribute is not serialized.
[XmlIgnore]
Public int Speed {get; set ;}
 
// Serialize the Saying attribute to an Xml sub-element.
[XmlElement ("saying")]
Public string Saying {get; set ;}
}
}
The above code will be output: <? Xml version = "1.0" encoding = "gb2312"?>
<Cats xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http: // ww
Export 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>


 

Related Article

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.