Home Backend Development XML/RSS Tutorial Sample code analysis of Xml serialization and deserialization of XmlSerializer objects

Sample code analysis of Xml serialization and deserialization of XmlSerializer objects

Mar 09, 2017 pm 04:57 PM

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();
    }
}
Copy after login

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>
Copy after login

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();
    }
}
Copy after login

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; }
    }
}
Copy after login

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; }
    }
}
Copy after login

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>
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve php deserialization failure How to solve php deserialization failure Oct 11, 2023 am 09:30 AM

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.

How does the C++ function library perform serialization and deserialization? How does the C++ function library perform serialization and deserialization? Apr 18, 2024 am 10:06 AM

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 PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Jul 29, 2023 am 10:49 AM

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?

Serialization and deserialization of interfaces and abstract classes in Java Serialization and deserialization of interfaces and abstract classes in Java May 02, 2024 am 08:33 AM

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.

High performance serialization and deserialization technology in PHP High performance serialization and deserialization technology in PHP Jun 22, 2023 pm 09:34 PM

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

Use PHP unserialize() function to implement deserialization Use PHP unserialize() function to implement deserialization Jun 27, 2023 am 08:01 AM

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

Object serialization and deserialization in Go language Object serialization and deserialization in Go language Jun 03, 2023 am 08:31 AM

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.

How to deserialize Java objects from Reader stream in Java using flexjson? How to deserialize Java objects from Reader stream in Java using flexjson? Sep 10, 2023 pm 10:57 PM

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{

See all articles