Microsoft has realized the importance of serialized data, so it has included the namespace System.Runtime.Serialization and System.Xml.Serialization in the .NET framework to provide serialization functions and provide users with the ability to write their own serialization methods. a framework. The System.Xml.Serialization namespace provides basic methods for serializing an object into XML format. Let's take a look at how to use this method.
The charm of XML
Serialized XML refers to the process of saving the public fields and attributes of an object into a serial format (here, XML format) for the convenience of storage or transmission. Deserialization is the process of using serial state information to restore an object from its serial XML state to its original state. Therefore, you can think of serialization as a method of saving the state of an object to a stream or buffer.
The purpose of serialization is data storage and data conversion. Data storage refers to saving data across user sessions. When the application is closed, the data is saved (serialized) and when the user comes back, the data is reloaded (deserialized). Data conversion refers to transforming data into a format that can be understood by another system. Using serialization and XML, data conversion can be easily performed.
The data in the object can be a class, method, property, private type, array, or even embedded XML in a System.Xml.XmlElement or System.Xml.XmlAttribute object.
The key class in the System.Xml.Serialization namespace is XmlSerializer. Of course, this namespace also includes other classes related to other aspects of XML and SOAP, but our focus is on the XmlSerializer class.
XmlSerializer
The XmlSerializer class provides methods for serializing objects into XML files and deserializing XML documents into objects. It also allows users to specify how objects are converted to XML. You can pass the type of object to be serialized as a parameter to the class constructor. The following C# code illustrates the use of the 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 calling TextWriter, Stream and XmlWriter objects during serialization. The following example code illustrates how to call this method. In this example an object is serialized and saved to a file on the local disk. The example starts with 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 above code turns three objects into one object, thus generating an XML file during the serialization process. The following is the XML document generated by the example program:
<?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 handle nesting of object data. The data is converted into a recognizable format, which facilitates data reloading (deserialization) and data transfer to another system. During the data transfer process, the receiving system needs to know the format of the XML file (if it does not know it in advance). Therefore, an XML schema file needs to be provided. The XSD.exe tool in the .NET Framework 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
ImportsSystem.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 With
ser.Serialize(writer, BookObject)
writer.Close()
End Sub
End Module
control output
The serialization process generates standard XML files and data members are converted into XML elements. However, not all data members become elements. You can control the output XML file by adding some tags in the class code. This way, data members can be converted to XML attributes rather than elements, or simply ignored. The following example is 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 an XML attribute when generating the XML file, and ignore 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</Address1>
<City>Anywhere</City>
<State>KY</State>
<Zip>40000</Zip>
<Country>USA</Country>
</AddressObject>
</AuthorObject>
<Title>Practical LotusScript</Title>
<Publisher>Manning Publications</Publisher>
</Book>
The following is the corresponding C# code:
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;
}
The above only briefly mentions two marking symbols. Please consult the .NET documentation for complete markup notation.
Deserializing deserialized data can be easily achieved by calling the Deserialize method of the XmlSerializer class. The following VB.NET program fragment completes the deserialization of the XML document mentioned above:
Dim BookObject As New Book
Dim 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 memory for later use. Here 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));
-------------------------------------------------- -
About the author: Tony Patton is a professional application developer with extensive knowledge and is certified in Java, VB, Lotus, and XML.