


Sample code analysis of Xml serialization and deserialization of XmlSerializer objects
The .Net namespace corresponding to this essay is System.Xml.Serialization; the sample code in the article needs to reference this namespace.
Why do we need to serialize and deserialize?
When the .Net program is executed, the objects reside in the memory; if the objects in the memory need to be passed to other systems for use; or need to be saved when shutting down so that they can be used again when the program is started again, they need to be serialized and deserialized. change.
Scope:This article only introduces xml serialization. In fact, serialization can be binary serialization or serialization in other formats.
Look at the simplest Xml serialization code
class Program { static void Main(string[] args) { int i = 10; //声明Xml序列化对象实例serializer XmlSerializer serializer = new XmlSerializer(typeof(int)); //执行序列化并将序列化结果输出到控制台 serializer.Serialize(Console.Out, i); Console.Read(); } }
The above code serializes int i and outputs the serialization result to the console. The output is as follows
<?xml version="1.0" encoding="gb2312"?> <int>10</int>
You can deserialize the above serialized xml with the following code
static void Main(string[] args) { using (StringReader rdr = new StringReader(@"<?xml version=""1.0"" encoding=""gb2312""?> <int>10</int>")) { //声明序列化对象实例serializer XmlSerializer serializer = new XmlSerializer(typeof(int)); //反序列化,并将反序列化结果值赋给变量i int i = (int)serializer.Deserialize(rdr); //输出反序列化结果 Console.WriteLine("i = " + i); Console.Read(); } }
The above code illustrates the xml serialization and deserialization process in the simplest way. The .Net system class library does it for us A lot of work, serialization and deserialization are very simple. However, in reality, business requirements are often more complex, and it is impossible to simply serialize an int variable. In display, we need to controllably serialize complex types.
Xml serialization of custom objects:
There are a series of feature classes in the System.Xml.Serialization namespace to control the serialization of complex types. For example, XmlElementAttribute, XmlAttributeAttribute, XmlArrayAttribute, XmlArrayItemAttribute, XmlRootAttribute, etc.
Look at a small example. There is a custom class Cat. The Cat class has three attributes: Color, Saying, and Speed.
namespace UseXmlSerialization { class Program { static void Main(string[] args) { //声明一个猫咪对象 var c = new Cat { Color = "White", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" }; //序列化这个对象 XmlSerializer serializer = new XmlSerializer(typeof(Cat)); //将对象序列化输出到控制台 serializer.Serialize(Console.Out, c); Console.Read(); } } [XmlRoot("cat")] public class Cat { //定义Color属性的序列化为cat节点的属性 [XmlAttribute("color")] public string Color { get; set; } //要求不序列化Speed属性 [XmlIgnore] public int Speed { get; set; } //设置Saying属性序列化为Xml子元素 [XmlElement("saying")] public string Saying { get; set; } } }
You can use XmlElement to specify attributes to be serialized into child nodes (by default, they will be serialized into child nodes); or use the The optimizer does not serialize modified properties.
Xml serialization of object array:
Xml serialization of array requires the use of XmlArrayAttribute and XmlArrayItemAttribute; XmlArrayAttribute specifies the Xml node name of the array element, and XmlArrayItemAttribute specifies the Xml node name of the array element.
The following code example:
/*玉开技术博客 http://www.php.cn/ */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace UseXmlSerialization { class Program { static void Main(string[] args) { //声明一个猫咪对象 var cWhite = new Cat { Color = "White", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" }; var cBlack = new Cat { Color = "Black", Speed = 10, Saying = "White or black, so long as the cat can catch mice, it is a good cat" }; CatCollection cc = new CatCollection { Cats = new Cat[] { cWhite,cBlack} }; //序列化这个对象 XmlSerializer serializer = new XmlSerializer(typeof(CatCollection)); //将对象序列化输出到控制台 serializer.Serialize(Console.Out, cc); Console.Read(); } } [XmlRoot("cats")] public class CatCollection { [XmlArray("items"),XmlArrayItem("item")] public Cat[] Cats { get; set; } } [XmlRoot("cat")] public class Cat { //定义Color属性的序列化为cat节点的属性 [XmlAttribute("color")] public string Color { get; set; } //要求不序列化Speed属性 [XmlIgnore] public int Speed { get; set; } //设置Saying属性序列化为Xml子元素 [XmlElement("saying")] public string Saying { get; set; } } }
The above code will output:
<?xml version="1.0" encoding="gb2312"?> <cats xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://ww w.w3.org/2001/XMLSchema"> <items> <item color="White"> <saying>White or black, so long as the cat can catch mice, it is a good cat</saying> </item> <item color="Black"> <saying>White or black, so long as the cat can catch mice, it is a good cat</saying> </item> </items> </cats>
situation , msdn description is as follows:
Dynamically generated assembly
To improve performance, the XML serialization infrastructure will dynamically generate assemblies to serialize and deserialize specified types. This infrastructure will find and reuse these assemblies. This behavior only occurs when using the following constructors: XmlSerializer(Type)
XmlSerializer. be unloaded, which will cause memory leaks and reduced performance. The simplest solution is to use one of the two constructors mentioned earlier. Otherwise, the assembly must be cached in a Hashtable, as shown in the following example.
That is to say, we are using XmlSerializer for serialization. When initializing the XmlSerializer object, it is best to use the following two constructors, otherwise it will cause memory leaks.
XmlSerializer(Type)
XmlSerializer.
The above is the detailed content of Sample code analysis of Xml serialization and deserialization of XmlSerializer objects. For more information, please follow other related articles on the PHP Chinese website!

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



Solution to PHP deserialization failure Check the serialized data. Check class definitions, check error logs, update PHP versions and apply security measures, etc. Detailed introduction: 1. Check the serialized data. First check whether the serialized data is valid and conforms to PHP's serialization specification. If the data is damaged or has an incorrect format, you can try to repair it or restore the correct data from backup; 2. Check Class definition, ensure that all classes used in serialized data exist and can be automatically loaded. If the class does not exist or is inaccessible, you can try to repair the class definition, etc.

C++ Library Serialization and Deserialization Guide Serialization: Creating an output stream and converting it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.

PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Serialization and deserialization are one of the commonly used data processing skills in computer science. In PHP, we can use the serialize() and unserialize() functions to implement data serialization and deserialization operations. This article will give you a detailed introduction to how to use these two functions and provide relevant code examples. 1. What is serialization and deserialization in computer programming?

Interfaces cannot be serialized directly. Abstract classes can be serialized but only if they do not contain non-static, non-transient fields or override the writeObject() and readObject() methods. Specific instances can be implemented through concrete classes that implement the interface or override writeObject() and readObject. Abstract class implementation of () method.

Serialization is the process of converting data structures or objects into a transmittable data format, while deserialization is the process of restoring these data to the original objects or data structures. In web development, serialization and deserialization technologies are widely used in scenarios such as data transmission, caching, and distributed computing. As a commonly used web back-end development language, how are PHP's built-in serialization and deserialization functions implemented? This article will introduce serialization in PHP

Serialization is the process of converting a data structure or object into a string for storage, transmission, or representation, and conversely, parsing a string into the original data structure or object. In PHP, we can use the serialize() function to serialize a variable into a string, and use the unserialize() function to deserialize a string into a primitive data structure or object. This article will focus on the use and precautions of the PHPunserialize() function. 1. unserialize

With the application of distributed server technology, the function of object serialization and deserialization has become more and more mundane in programmers' work. The Go language also provides a variety of ways to implement object serialization and deserialization, and the usage scenarios of these methods are also different. This article will introduce in detail the implementation of object serialization and deserialization in Go language and how to use it. 1. What is object serialization and deserialization? Object serialization and deserialization refers to converting an object data structure into a storable or transferable form to facilitate subsequent operations.

Flexjson is a lightweight library for serializing and deserializing Java objects to and from JSON format. We can deserialize a Java object from a Reader stream using the deserialize() method of the JSONDeserializer class, which uses an instance of the Reader class as the JSON input. Syntax publicTdeserialize(Readerinput) example importjava.io.*;importflexjson.JSONDeserializer;publicclassJSONDeserializeReaderTest{
