. NET object XML serialization and deserialization

Source: Internet
Author: User
Tags object serialization
. NET object XML serialization and deserialization [url = javascript: d = document; t = d. selection? (D. selection. type! = 'None '? D. selection. createRange (). text: '') :( d. getSelection? D. getSelection (): ''); void (saveit = window. open ('HTTP: // wz.csdn.net/storeit.aspx? T = '+ escape (d. title) + '& u =' + escape (d. location. href) + '& c =' + escape (t), 'saveid', 'scrollbars = no, width = 590, height = 300, left = 75, top = 20, status = no, resizable = yes '); saveit. focus ();] add to favorites [/url] serialization concepts
Serialization means that an object instance can be saved as a binary string. Of course, once saved as a binary string, it can also be saved as a text string.
For example, if the value of a counter is 2, we can use the string "2.
If there is an object called connter with the current value of 2, it can be serialized to "2", reverse, or a counter instance with the value of 2 can be obtained from "2.
In this way, it will be serialized when it is shut down, and deserialized when it is turned on. Each time it is started, it will continue. Not all from the beginning.
The introduction and implementation of the serialization concept makes it easier to save and read the setting information of our applications.
Serialization has many advantages. For example, an instance is generated on one machine, initialized, serialized, transmitted over the network to another machine, and deserialized to get the object instance, then execute some business logic, get the result, serialize it, return the first machine, the first machine gets the object instance, and get the result.
This example shows the advanced principle of "intelligent proxy.
Currently, popular web services use the soap protocol, and the soap protocol is also based on object serialization.
I. Overview
. NET Framework provides many different class libraries for processing XML data. The XmlDocument class allows you to process xml data like a file, while XmlReader, XmlWriter, and Their Derived classes allow you to process xml data as data streams.
XmlSerializer provides another method that enables you to serialize and deserialize your objects into xml. Serialized data not only allows you to process data randomly like a file, but also skips data that you are not interested in.
II. Introduction to main class libraries
. NET class libraries that support object xml Serialization and deserialization are mainly located in the namespace System. Xml. Serialization.
1. XmlSerializer class
This class provides serialized services in a highly loosely coupled manner. Your classes do not need to inherit Special Base classes, and they do not need to implement special interfaces. Instead, you only need to add custom features to your class or the public domains of these classes and read/write attributes. XmlSerializer uses the reflection mechanism to read these features and map your Class and Class Members to xml elements and attributes.
2. XmlAttributeAttribute class
The public domain or read/write Attribute of the specified class corresponds to the Attribute of the xml file.
Example: [XmlAttribute ("type")] or [XmlAttribute (AttributeName = "type")]
3. XmlElementAttribute class
Specifies the public domain of the class or the read/write attribute corresponding to the Element of the xml file.
Example: [XmlElement ("Maufacturer")] or [XmlElement (ElementName = "Manufacturer")]
4. XmlRootAttribute class
During Xml serialization, the elements specified by this feature are serialized into the root element of xml.
Example: [XmlRoot ("RootElement")] or [XmlRoot (ElementName = "RootElements")]
5. XmlTextAttribute class
During Xml serialization, the element values specified by this feature are serialized into the values of xml elements. Only one instance of this feature class is allowed for a class, because the xml element can have only one value.
6. XmlIgnoreAttribute class
Elements specified by this feature are not serialized during Xml serialization.
Three instances
The xml schema in The following example describes a simple human resource information, which contains most of the xml formats. For example, xml elements are nested with each other. xml elements have both element values and attribute values.
1. Hierarchy of classes to be serialized
[XmlRoot ("humanResource")]
Public class HumanResource
{
# Region private data.
Private int m_record = 0;
Private Worker [] m_workers = null;
# Endregion

[XmlAttribute (AttributeName = "record")]
Public int Record
{
Get {return m_record ;}
Set {m_record = value ;}
}

[XmlElement (ElementName = "worker")]
Public Worker [] Workers
{
Get {return m_workers ;}
Set {m_workers = value ;}
}
}

Public class Worker
{
# Region private data.
Private string m_number = null;
Private InformationItem [] m_infoItems = null;
# Endregion

[XmlAttribute ("number")]
Public string Number
{
Get {return m_number ;}
Set {m_number = value ;}
}

[XmlElement ("infoItem")]
Public InformationItem [] InfoItems
{
Get {return m_infoItems ;}
Set {m_infoItems = value ;}
}
}

Public class InformationItem
{
# Region private data.
Private string m_name = null;
Private string m_value = null;
# Endregion

[XmlAttribute (AttributeName = "name")]
Public string Name
{
Get {return m_name ;}
Set {m_name = value ;}
}

[XmlText]
Public string Value
{
Get {return m_value ;}
Set {m_value = value ;}
}
}
2. serialized xml structure
<? Xml version = "1.0"?>
[Url = file: // E:/humans. xml #]-[/Url] [Url = file: // E:/humans. xml #]-[/Url] <worker number ="001">
<InfoItem name ="Name">Michale</InfoItem>
<InfoItem name ="Sex">Male</InfoItem>
<InfoItem name ="Age">25</InfoItem>
</Worker>
[Url = file: // E:/humans. xml #]-[/Url] <worker number ="002">
<InfoItem name ="Name">Surce</InfoItem>
<InfoItem name ="Sex">Male</InfoItem>
<InfoItem name ="Age">28</InfoItem>
</Worker>
</HumanResource>
3. Implement serialization and deserialization using the XmlSerializer class (generally, xml files are parsed only once using the cache mechanism .)
Public sealed class ConfigurationManager
{
Private static HumanResource m_humanResource = null;
Private ConfigurationManager (){}

Public static HumanResource Get (string path)
{
If (m_humanResource = null)
{
FileStream fs = null;
Try
{
XmlSerializer xs = new XmlSerializer (typeof (HumanResource ));
Fs = new FileStream (path, FileMode. Open, FileAccess. Read );
M_humanResource = (HumanResource) xs. Deserialize (fs );
Fs. Close ();
Return m_humanResource;
}
Catch
{
If (fs! = Null)
Fs. Close ();
Throw new Exception ("Xml deserialization failed! ");
}

}
Else
{
Return m_humanResource;
}
}

Public static void Set (string path, HumanResource humanResource)
{
If (humanResource = null)
Throw new Exception ("Parameter humanResource is null! ");

FileStream fs = null;
Try
{
XmlSerializer xs = new XmlSerializer (typeof (HumanResource ));
Fs = new FileStream (path, FileMode. Create, FileAccess. Write );
Xs. Serialize (fs, humanResource );
M_humanResource = null;
Fs. Close ();
}
Catch
{
If (fs! = Null)
Fs. Close ();
Throw new Exception ("Xml serialization failed! ");
}
}
}
Iv. Description
1. the attribute to be serialized as an xml element must be a read/write attribute;
2. Set the default value for the class member, although this is not necessary.

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.