XML serialization and deserialization of. NET objects

Source: Internet
Author: User
Tags object serialization xml attribute

Serialization Concept
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"?>
-<HumanResource xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: xsd = "http://www.w3.org/2001/XMLSchema" record = "2">
-<Worker number = "001">
<InfoItem name = "name"> Michale </infoItem>
<InfoItem name = "sex"> male </infoItem>
<InfoItem name = "age"> 25 </infoItem>
</Worker>
-<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.
About serialization in. NET
Serialization can be defined as the process of storing the object state to the storage media. In this process, the public and private fields of the object and the name of the class (including the Assembly containing the class) are converted into byte streams and then written into the data stream. When you "deserialize" this object in the future, create an exact copy of the original object.
I. Why serialization?
One reason is to keep the object state in the storage media so that you can recreate a precise copy later;
Another reason is that an object is sent from one application domain to another by value.
For example, serialization can be used to save the session state in ASP. NET and copy the object to the clipboard of Windows Forms. Remote processing can also use serialization to pass objects from one application domain to another through values.
Ii. How to Implement Object serialization and deserialization
To serialize an object, ensure that the object can be serialized. In addition, serialization only saves the object attributes effectively, but some methods of the object cannot be serialized.
The easiest way to implement Serializable class serialization is to add the Serializable attribute tag class. For example:
[Serializable ()]
Public class MEABlock
{
Private int m_ID;
Public string Caption;

Public MEABlock ()
{
/// Constructor
}
}
This class can be serialized.
To serialize the instance of this class to a file ?. NET FrameWork provides two methods:
1. XML serialization
Use the XmLSerializer class to serialize the following items.

Public read/write attributes and fields of public classes
Class that implements ICollection or IEnumerable. (Note that only the set will be serialized, but the public attribute will not .)
XmlElement object.
XmlNode object.
DataSet object.
To serialize instances of the above classes, refer to the following example:
MEABlock myBlock = new MEABlock ();
// Insert code to set properties and fields of the object.
XmlSerializer mySerializer = new XmlSerializer (typeof (MEABlock ));
// To write to a file, create a StreamWriter object.
StreamWriter myWriter = new StreamWriter ("myFileName. xml ");
MySerializer. Serialize (myWriter, MEABlock );
Note that XML serialization only saves public fields and does not save private fields.
The generated XML file format is as follows:
<MEABlock>
<Caption> Test </Caption>
</MEABlock>
The deserialization of objects is as follows:
MEABlock myBlock;
// Constructs an instance of the XmlSerializer with the type
// Of object that is being deserialized.
XmlSerializer mySerializer = new XmlSerializer (typeof (MEABlock ));
// To read the file, creates a FileStream.
FileStream myFileStream = new FileStream ("myFileName. xml", FileMode. Open );
// Callthe Deserialize method and casts to the object type.
MyBlock = (MEABlock) mySerializer. Deserialize (myFileStream)
2. binary serialization
Different from XML serialization, binary serialization can serialize all fields (both private and public) in the instance of the class. This makes it easier and more accurate to restore copies of objects.
To serialize instances of the above classes, refer to the following example:
MEABlock myBlock = new MEABlock ();
// Insert code to set properties and fields of the object.
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("MyFile. bin", FileMode. Create, FileAccess. Write, FileShare. None );
Formatter. Serialize (stream, myBlock );
Stream. Close ();
The deserialization of objects is as follows:
IFormatter formatter = new BinaryFormatter ();
Stream stream = new FileStream ("MyFile. bin", FileMode. Open, FileAccess. Read, FileShare. Read );
MEABlock myBlock = (MEABlock) formatter. Deserialize (stream );
Stream. Close ();

3. How to serialize and deserialize custom visual controls in disguise
Custom Controls in WinForm are inherited from System. windows. form class, while Form class is inherited from MarshalByRefObject, the Form itself cannot be serialized, the Form implementation is based on the Win32 GUI resources, cannot be separated from the current context.
Of course, you can use a work und to serialize controls. The memory model is used here.
The definition memory class (actually a serializable entity class) is used to record the valid properties of the Control. to serialize the control, you only need to Copy the instance of the control to the memory class, it is serialized to save the memory class.
Deserialization is an inverse process. Deserializes data streams into the memory class, and generates control instances based on the attributes of the memory class. You can continue to use some events and methods of controls.

Introduction to XML serialization

. NET Framework developer Guide

Serialization is the process of converting an object into a format that is easy to transmit. For example, you can serialize an object and Use HTTP to transmit the object between the client and the server over the Internet. At the other end, deserialization reconstructs the object from the stream.
XML serialization only serializes public fields and attribute values of objects into XML streams. XML serialization does not include type information. For example, if you have a Book object in the Library namespace, it cannot be guaranteed that it will be deserialized into the same type of object.

Note that XML serialization does not convert methods, indexers, private fields, or read-only attributes (except for read-only sets ). To serialize all fields and attributes of an object (public and private), use BinaryFormatter instead of XML serialization.
The most important class in XML serialization is the XmlSerializer class. The most important method is the Serialize and Deserialize methods. XML streams generated by XmlSerializer comply with the recommendations of the World Wide Web Federation (http://www.w3.org/) XML Schema Definition Language (XSD) 1.0. In addition, the generated data type conforms to the document titled "XML Schema Part 2: Datatypes" (XML architecture Part 2: Data Type.

The data in the object is described in programming languages (such as classes, fields, attributes, primitive types, arrays, and even embedded XML in the form of XmlElement or XmlAttribute objects. You can create your own class with attribute annotation, or use the XML schema definition tool to generate a class based on the existing XML schema.

If you have an XML schema, you can run the XML schema definition tool to generate a group of classes that are strongly typed into the schema and annotated with attributes. When such classes are serialized, the generated XML conforms to the XML architecture. With such a class, you can program the object model that is easy to operate, and ensure that the generated XML conforms to the XML architecture. This is a replacement method for analyzing and writing XML streams using other classes in. NET Framework (such as XmlReader and XmlWriter. (For more information about using these classes, see using XML in. NET Framework .) These classes allow you to analyze any XML stream. In contrast, use XmlSerializer when an XML Stream is required to conform to a known XML schema.

Attributes control the XML Stream Generated by the XmlSerializer class, so that you can set the XML namespace, element name, and attribute name of the XML stream. For more information about these attributes and how they control XML serialization, see use attributes to control XML serialization. To obtain a table listing the attributes that control the generated XML, see controlling the attributes of XML serialization.

The XmlSerializer class can further serialize the object and generate the encoded soap xml stream. The generated XML conforms to section 1.1 of the World Wide Web Federation documentation titled "Simple Object Access Protocol (SOAP) 5th. For more information about this process, see generating SOAP messages using XML serialization. For details about controlling the generated XML Attribute Table, see controlling the attributes of SOAP serialization for encoding.

The XmlSerializer class generates a SOAP message created by XML Web services and passed to XML Web services. To control SOAP messages, you can apply attributes to classes, return values, parameters, and fields in the XML Web services file (. asmx. You can also use the attributes listed in "attributes for controlling XML serialization" and the attributes listed in "attributes for controlling encoding SOAP serialization, because XML Web services can use text styles or encoded SOAP styles. For more information about using properties to control the XML generated by XML Web services, see XML serialization of XML Web services. For more information about SOAP and XML Web services, see custom SOAP messages.

Protect XmlSerializer applications
When creating an application that uses XmlSerializer, you should understand the following and their impact:

XmlSerializer creates a C # file (. cs file), and compile it. dll files. dll files are located in the directory specified by the TEMP environment variable. These DLL files are serialized.
When code and DLL are created and compiled, they are vulnerable to malicious processes. If the computer is running Microsoft Windows NT 4.0 or later, two or more users may share the temporary directory. Shared temporary directories are dangerous if both of the following conditions exist: (1) two accounts have different security privileges; (2) an account with high privileges runs an application using XmlSerializer. In this case, a user can replace the compiled. cs or. dll file, thus compromising the computer security. To avoid this problem, always make sure that each account on the computer has its own configuration file. If this can be ensured, by default, the TEMP environment variable will specify different directories for different accounts.

If a malicious user sends continuous XML data streams (DoS attacks) to the Web server, XmlSerializer will process the data until the computer resources are insufficient.
If your computer runs Internet Information Service (IIS) and your application runs under IIS, you can avoid such attacks. IIS has a control gate used to prohibit the processing of data streams larger than the set quantity (4 KB by default. If the application you created does not use IIS and the application uses XmlSerializer for deserialization, a similar control gate should be implemented to prevent DoS attacks.

XmlSerializer will use any type given to it to serialize the data and run any code.
There are two ways to apply threats to malicious objects. One is to run malicious code, and the other is to insert malicious code into the C # File Created by XmlSerializer. In the first case, if a malicious object tries to run a destructive process, code access security will help prevent any damages. In the second case, theoretically, malicious objects may insert code to the C # File Created by XmlSerializer in some way. Although this problem has been thoroughly tested and is considered impossible, you should be careful not to serialize untrusted unknown data.

Serialized important data may be vulnerable to attacks.
After XmlSerializer serializes the data, the data can be stored as an XML file or in other data storage areas. If other processes can access your data storage area, or you can view the data storage area on the Intranet or the Internet, the data may be stolen and maliciously used. For example, if you create an application that serializes orders containing credit card numbers, this data is very important. To prevent this problem, always protect your data storage zone and keep your data confidential.

Serialization of simple classes
The following example shows a simple class with public fields:

[Visual Basic] Public Class OrderForm Public OrderDate As DateTimeEnd Class [C #] public class OrderForm {public DateTime OrderDate;} When serializing an instance of this type, this instance may be similar to the following code:

<OrderForm> <OrderDate> 12/12/01 </OrderDate> </OrderForm> For more examples of serialization, see XML serialization examples.

Serializable items
Use the XmLSerializer class to serialize the following items.

Public read/write attributes and fields of public classes
Class that implements ICollection or IEnumerable. (Note that only the set will be serialized, but the public attribute will not .)
XmlElement object.
XmlNode object.
DataSet object.
Serialization and deserialization objects
To serialize an object, first create the object to be serialized and set its public attributes and fields. Therefore, you must determine the transmission format (either as a stream or as a file) to store the XML stream ). For example, if the XML stream must be permanently saved, A FileStream object is created. When you deserialize an object, the transmission format determines whether you will create a stream or a file object. After determining the transmission format, you can call the Serialize or Deserialize method as needed.

Serialized object

Create an object and set its public fields and attributes.
Use the object type to construct XmlSerializer. For more information, see XmlSerializer class constructor.
Call the Serialize method to generate the XML Stream or file representation of the Public attributes and fields of the object. The following example creates a file.
[Visual Basic] Dim myObject As MySerializableClass = New MySerializableClass () 'insert code to set properties and fields of the object. dim mySerializer As XmlSerializer = New XmlSerializer (GetType (MySerializableClass) 'To write to a file, create a StreamWriter object. dim myWriter As StreamWriter = New StreamWriter ("myFileName. xml ") mySerializer. serialize (myWriter, myObject) [C #] MySerializableClass myObject = new MySerializableClass (); // Insert code to set properties and fields of the object. xmlSerializer mySerializer = new XmlSerializer (typeof (MySerializableClass); // To write to a file, create a StreamWriter object. streamWriter myWriter = new StreamWriter ("myFileName. xml "); mySerializer. serialize (myWriter, myObject); deserialization object

Construct XmlSerializer using the type of the object to be deserialized.
Call the Deserialize method to generate a copy of the object. During deserialization, the returned object must be forcibly converted to the type of the original object, as shown in the following example. The following example deserializes the object into a file, although it can also be deserialized into a stream.
[Visual Basic] Dim myObject As MySerializableClass 'constructs an instance of the XmlSerializer with the type' of object that is being deserialized. dim mySerializer As XmlSerializer = New XmlSerializer (GetType (MySerializableClass) 'To read the file, creates a FileStream. dim myFileStream As FileStream = _ New FileStream ("myFileName. xml ", FileMode. open) 'calls the Deserialize method and casts to the o Bject type. myObject = CType (_ mySerializer. deserialize (myFileStream), MySerializableClass) [C #] MySerializableClass myObject; // Constructs an instance of the XmlSerializer with the type // of object that is being deserialized. xmlSerializer mySerializer = new XmlSerializer (typeof (MySerializableClass); // To read the file, creates a FileStream. fileStream myFileStream = new FileStream ("myFileName. xml ", FileMode. open); // callthe Deserialize method and casts to the object type. myObject = (MySerializableClass) mySerializer. for more examples of XML serialization, see XML serialization examples.

Benefits of using XML serialization
The XmlSerializer class provides complete and flexible control when you serialize an object to XML. If you are creating XML Web services, you can apply attributes that control serialization to classes and members to ensure that the XML output conforms to the specific architecture.

For example, XmlSerializer enables you:

Specify whether fields or attributes should be encoded as features or elements.
Specify the XML namespace to use.
If the field or attribute name is inappropriate, specify the element or attribute name.
Another advantage of XML serialization is that as long as the generated XML Stream conforms to the given architecture, there is no constraint on the developed application. Assume that there is an architecture used to describe a book that has a title, author, publisher, and ISBN number element. You can develop an application that processes XML data in any way you want (for example, as a book order, or as a book list. In either case, the only requirement is that the XML stream should comply with the specified XML Schema Definition Language (XSD) architecture.

Notes for XML serialization
When using the XmlSerializer class, consider the following situations:

Serialized data only contains the data itself and the structure of the class. Does not include the type identifier and assembly information.
Only public attributes and fields can be serialized. To serialize non-public data, use the BinaryFormatter class instead of XML serialization.
The class must have a default constructor serialized by XmlSerializer.
The method cannot be serialized.
XmlSerializer can process classes that implement IEnumerable or ICollection in different ways (the condition is that these classes meet certain requirements ). The class implementing IEnumerable must implement the public Add method with a single parameter. The parameters of the Add method must be consistent with the type returned by the IEnumerator. Current attribute returned by the GetEnumerator method (polymorphism ). In addition to implementing IEnumerable, ICollection classes (such as CollectionBase) must have a public Item index attribute that takes an integer (in C #, It is the indexer ), and it must have a public Count attribute of the integer type. Parameters passed to the Add method must be of the same type returned from the Item attribute or a base type of the type. For classes that implement ICollection, the value to be serialized will be retrieved from the index Item attribute, rather than by calling GetEnumerator. Besides returning public fields of another collection class (the collection class implementing ICollection), public fields and attributes are not serialized. For examples, see XML serialization examples.
XSD data type ing
The World Wide Web Federation (http://www.w3.org/) document titled "XML Schema Part 2: PES ypes" specifies the simple data types that are allowed in the XML Schema Definition Language (XSD) architecture. For many types of these data types (such as int and decimal), there are corresponding data types in. NET Framework. However, some XML data types do not have corresponding data types in. NET Framework (for example, NMTOKEN data types ). In this case, if you use the XML schema definition tool (Xsd.exe) to generate classes from the schema, the appropriate features will be applied to members of the string type, the DataType attribute is set to the XML data type name. For example, if the schema contains an element named "MyToken" whose data type is xml nmtoken, the generated class may contain members in the following example.

[Visual Basic] <XmlElement (DataType: = "NMTOKEN")> Public MyToken As String [C #] [XmlElement (DataType = "NMTOKEN")] public string MyToken; similar to this, if you create a class that must comply with the specific XML Schema (XSD), you should apply the appropriate features and set its DataType attribute to the required XML data type name.

For a complete list of Type ing, see DataType attributes of any of the following feature classes: SoapAttributeAttribute, SoapElementAttribute, XmlArrayItemAttribute, XmlAttributeAttribute, XmlElementAttribute, or XmlRootAttribute.

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/shizhiyingnj/archive/2007/02/11/1507943.aspx

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.