Use XMLSerializer to serialize objects to XML

Source: Internet
Author: User
Microsoft has realized the importance of serialized data, so in. the. NET Framework contains the namespace System. runtime. serialization and System. xml. serialization provides the Serialization function and provides a framework for writing Serialization methods. The System. Xml. Serialization namespace provides the basic method to serialize an object into XML format. Let's take a look at how to use this method. Microsoft has realized the importance of serialized data, so in. the. NET Framework contains the namespace System. runtime. serialization and System. xml. serialization provides the Serialization function and provides a framework for writing Serialization methods. The System. Xml. Serialization namespace provides the basic method to serialize an object into XML format. Let's take a look at how to use this method.

XML charm

Serialized XML refers to the process of saving the public domain and attributes of an object as a serial format (XML format here) for convenient storage or transmission. Non-serializability refers to the process of restoring an object from the serial XML State to the original state using the serial state information. Therefore, serialization can be seen as a way to save the object State to a stream or a buffer.

The purpose of serialization is data storage and data conversion. Data storage refers to saving data during user sessions. When the application is closed, the data is saved (serialized), and when the user returns, the data is Reloaded (non-serialized ). Data conversion refers to converting data into a format recognized by another system. Data can be easily converted using serialization and XML.

The data in an object can be a class, method, attribute, private type, or array. in the System. Xml. XmlElement or System. Xml. XmlAttribute object, it can even be embedded XML.

The key class in the System. Xml. Serialization namespace is XmlSerializer. Of course, this namespace also includes other XML and SOAP-related classes, but our focus is on the XmlSerializer class.

XmlSerializer
The XmlSerializer class provides the method of serializing an object into an XML file and non-serializing an XML document into an object. It also allows users to specify how objects are converted to XML. The type of the serialized object can be used as a parameter of the class constructor. The following C # code illustrates the usage of constructor.

    XmlSerializer ser = new XmlSerializer(typeof(objectToSerialize));

The following is the equivalent VB. NET code:

    Dim ser As New XmlSerializer(GetType(objectToSerialize))

The actual serialization process is implemented in the Serialize method of the XmlSerializer class. This method allows you to call TextWriter, Stream, and XmlWriter objects during serialization. The example code below illustrates how to call this method. In this example, an object is serialized and saved to a local disk. In this example, the first is the class declaration, followed by the serialized source code.

using System;namespace BuilderSerialization {public class Address {public Address() {}public string Address1;public string Address2;public string City;public string State;public string Zip;public string Country;} }using System;namespace BuilderSerialization {public class Author {public Author() { }public string FirstName;public string MiddleName;public string LastName;public string Title;public string Gender;public Address AddressObject;} }namespace BuilderSerialization {public class Book {public Book() { }public string Title;public Author AuthorObject;public string ISBN;public double RetailPRice;public string Publisher;}}using System;using System.Xml.Serialization;using System.IO;namespace BuilderSerialization {class TestClass {static void Main(string[] args) {Book BookObject = new Book();XmlSerializer ser = new XmlSerializer(typeof(Book));TextWriter writer = new StreamWriter("booktest.xml");BookObject.Title = "Practical LotusScript";BookObject.ISBN = "1884777767 ";BookObject.Publisher = "Manning Publications";BookObject.RetailPrice = 43.95;BookObject.AuthorObject = new Author();BookObject.AuthorObject.FirstName = "Tony";BookObject.AuthorObject.LastName = "Patton";BookObject.AuthorObject.Gender = "Male";BookObject.AuthorObject.AddressObject = new Address();BookObject.AuthorObject.AddressObject.Address1 = "1 Main Street";BookObject.AuthorObject.AddressObject.City = "Anywhere";BookObject.AuthorObject.AddressObject.State = "KY";BookObject.AuthorObject.AddressObject.Zip = "40000";BookObject.AuthorObject.AddressObject.Country = "USA";ser.Serialize(writer, BookObject);writer.Close();} } }

The code above changes three objects into one object, so an XML file is generated during serialization. The XML document generated by the example program is as follows:

 
 
  Practical LotusScript
  
   Tony
  
  
   Patton
  
  
   Male
  1 Main Street
  
   Anywhere
  
  
   KY
  
  
   40000
  
  
   USA
  
  
   1884777767 
  
  
   43.95
  
  
   Manning Publications
  
 

Note that the serialization process can also process object data nesting. The data is converted to a recognizable format, facilitating data overloading (non-serializing) and data transmission to another system. During data transmission, the recipient's system needs to know the XML file format (if not known in advance ). Therefore, you must provide an XML schema file .. The xsd.exe tool in the netframework can generate a schema file for serialized XML.

The following is an example code written in VB. NET:

Public Class AddressPublic Address1 As StringPublic Address2 As StringPublic City As StringPublic State As StringPublic Zip As StringPublic Country As StringEnd ClassPublic Class AuthorPublic FirstName As StringPublic MiddleName As StringPublic LastName As StringPublic Title As StringPublic Gender As StringPublic AddressObject As AddressEnd ClassPublic Class BookPublic AuthorObject As AuthorPublic Title As StringPublic ISBN As StringPublic RetailPrice As DoublePublic Publisher As StringEnd ClassImports System.Xml.SerializationImports System.IOModule Module1Sub Main()Dim BookObject As New BookDim ser As New XmlSerializer(GetType(Book))Dim writer As New StreamWriter("booktest.xml")With BookObject.Title = "Practical LotusScript".ISBN = "1884777767 ".Publisher = "Manning Publications".RetailPrice = 43.95.AuthorObject = New Author.AuthorObject.FirstName = "Tony".AuthorObject.LastName = "Patton".AuthorObject.Gender = "Male".AuthorObject.AddressObject = New Address.AuthorObject.AddressObject.Address1 = "1 Main Street".AuthorObject.AddressObject.City = "Anywhere".AuthorObject.AddressObject.State = "KY".AuthorObject.AddressObject.Zip = "40000".AuthorObject.AddressObject.Country = "USA"End Withser.Serialize(writer, BookObject)writer.Close()End SubEnd Module

Control Output

The serialization process generates standard XML files, and data members are converted to XML elements. However, not all data members become elements. you can add some tags to the class code to control the output XML file. In this way, data members can be converted to XML attributes rather than elements, or simply ignored. The following example shows a modified book Class VB. NET code.

Public Class BookPublic AuthorObject As AuthorPublic Title As String
 
   _Public ISBN As String
  
    _Public RetailPrice As DoublePublic Publisher As StringEnd Class
  
 

This code tells the system to use the class member ISBN as the XML attribute when generating the XML file, while ignoring the RetailPrice member. This change can be seen in the generated XML file:

 
 
  
   Tony
  
  
   Patton
  
  
   Male
  1 Main Street
  
   Anywhere
  
  
   KY
  
  
   40000
  
  
   USA
  
  Practical LotusScript
  
   Manning Publications
  
 

The corresponding C # code is as follows:

public class Book {public Book() { }public string Title;public Author AuthorObject;[System.Xml.Serialization.XmlAttribute()]public string ISBN;[System.Xml.Serialization.XmlIgnoreAttribute()]public double RetailPrice;public string Publisher;}

There are only two types of markup symbols mentioned above. Please refer to the. NET documentation for the complete markup.

Non-Serializable
Non-serialized data can be conveniently implemented by calling the Deserialize method of the XmlSerializer class. The following VB. NET program snippets complete the non-serialization of the XML document above:

Dim BookObject As New BookDim ser As New XmlSerializer (GetType (Book) Dim fs As New System. IO. fileStream ("booktest. xml ", FileMode. open) Dim reader As New System. XML. xmlTextReader (fs) BookObject = CType (ser. deserialize (reader), Book) This program puts the result data into the memory for backup. The following is the equivalent C # code: XmlSerializer ser = new XmlSerializer (typeof (Book); System. IO. fileStreamfs = new System. IO. fileStream ("booktest. xml ", FileMode. open); System. xml. xmlTextReader reader = new System. xml. xmlTextReader (fs); Book BookObject = (Book) (ser. deserialize (reader ));

The above code uses XMLSerializer to serialize objects to XML. For more information, see PHP Chinese website (www.php1.cn )!

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.