Use XMLSerializer to serialize objects to XML

Source: Internet
Author: User
Tags xml attribute

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 Lotus script ";
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:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Book xmlns: xsd = "http://www.w3.org/2001/XMLSchema"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance">
<Title> Practical LotusScript </Title>
<AuthorObject>
<FirstName> Tony </FirstName>
<LastName> Patton </LastName>
<Gender> Male </Gender>
<AddressObject>
<Address1> 1 Main Street </Address1>
<City> Anywhere </City>
<State> KY </State>
<Zip> 40000 </Zip>
<Country> USA </Country>
</AddressObject>
</AuthorObject>
<ISBN> 1884777767 </ISBN>
<RetailPrice> 43.95 </RetailPrice>
<Publisher> Manning Publications </Publisher>
</Book>

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 Address
Public Address1 As String
Public Address2 As String
Public City As String
Public State As String
Public Zip As String
Public Country As String
End Class
Public Class Author
Public FirstName As String
Public MiddleName As String
Public LastName As String
Public Title As String
Public Gender As String
Public AddressObject As Address
End Class
Public Class Book
Public AuthorObject As Author
Public Title As String
Public ISBN As String
Public RetailPrice As Double
Public Publisher As String
End Class
Imports System. Xml. Serialization
Imports System. IO
Module Module1
Sub Main ()
Dim BookObject As New Book
Dim 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
Ser. Serialize (writer, BookObject)
Writer. Close ()
End Sub
End 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 Book
Public AuthorObject As Author
Public Title As String
<System. Xml. Serialization. XmlAttribute ()> _
Public ISBN As String
<System. Xml. Serialization. XmlIgnoreAttribute ()> _
Public RetailPrice As Double
Public Publisher As String
End 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:

<? Xml version = "1.0" encoding = "UTF-8"?>
<Book xmlns: xsd = "http://www.w3.org/2001/XMLSchema"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" ISBN = "1884777767">
<AuthorObject>
<FirstName> Tony </FirstName>
<LastName> Patton </LastName>
<Gender> Male </Gender>
<AddressObject>
<Address1> 1 Main Street </Addres

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.