Home  >  Article  >  Backend Development  >  Serialize objects to XML using XMLSerializer

Serialize objects to XML using XMLSerializer

黄舟
黄舟Original
2017-03-02 17:24:311659browse

Microsoft has realized the importance of serialized data, so the .NET framework includes the namespaces System.Runtime.Serialization and System.xml.Serialization to provide serialization functions and allow users to write their own serialization Methods provide 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.

Charm of XML

Serialized XML refers to saving the public fields and attributes of an object in a serial format (here, XML format) for the convenience of storage or transmission. process. 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 classes, methods, properties, private types, arrays, and in System.Xml.XmlElement or System.Xml.XmlAttribute objects, it can even be embedded XML.

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 the 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
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 With
ser.Serialize(writer, BookObject)
writer.Close()
End Sub
End Module

Control output

The serialization process generates a standard XML file, and the 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;
}

Only two markup symbols are slightly mentioned above. Please consult the .NET documentation for complete markup notation.

Deserialization
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)
该程序把结果数据放入内存备用。下面是等价的C# 代码:
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 is the content of using XMLSerializer to serialize objects to XML. For more related content, please pay attention to the PHP Chinese website (www .php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn