Serialize objects to XML using XMLSerializer
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)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and
