Home Backend Development PHP Tutorial In-depth understanding: XML and object serialization and deserialization_PHP tutorial

In-depth understanding: XML and object serialization and deserialization_PHP tutorial

Jul 21, 2016 pm 03:07 PM
xml and main object Serialization article go deep understand of

This article mainly talks about the serialization and deserialization of XML and objects. And some simple serialization and deserialization methods will be attached for everyone to use.
Suppose we have two classes like this in a web project

Copy the code The code is as follows:

public class Member
{
public string Num { get; set; }
public string Name { get; set; }
}
public class Team
{
public string Name;
Public List Members { get; set; }
}

Suppose we need to POST an instance of the Team class to a URL,
Of course, use Form to hide the field Submit to complete this function.
What if the Team includes 30 pieces of data?
In order to distinguish each Member, we have to add a suffix to the parameter name. This requires a long list of hidden fields to complete:
Copy the code The code is as follows:


@model Team

< input type="hidden" name="TeamName" value="@Model.Name" />


...






Do you dare to imagine what would happen if Team was more complicated and nested more?
Well, even if you are willing to transfer data like this, it will be a headache for the other party to see a bunch of parameter names.
We all know that objects cannot be transmitted directly over the network, but there are remedies.
XML (Extensible Markup Language)Extensible Markup Language itself is designed to store data, and any object can be described in XML. Take the Team class as an example:
Copy the code The code is as follows:


& lt; name & gt; development & lt;/name & gt;
& lt; members & gt;
& lt;
& lt; num & gt 001 & lt;/num & gt;
& lt; name & gt; Marry & lt;/name & gt;
& lt;/member & gt;
& lt; member & gt hn & lt;/name & gt;
& lt;/ Member>




Such an XML document represents an instance of Team.
Smart readers should have already thought that XML can be used as a carrier of object information to be transmitted on the network because it is in text form.
How to convert XML documents and objects to and from each other?


The XmlSerializer class does this job.

Namespace: System.Xml.Serialization Assembly: System.Xml (in system.xml.dll)

Now shown here An EncodeHelper class that provides serialization and deserialization methods. The
Deserialize method converts an XML string into an object of a specified type; the

Serialize method converts an object into an XML string.

Copy code The code is as follows:

///
/// Provide xml document serialization and deserialization
///

public sealed class EncodeHelper
{
///
🎜>                                                                                   using (StringReader stringReader = new StringReader(Xml))
result = xmlSerializer.Deserialize(stringReader);
                                                                                       bool flag = false;
if (Xml != null)
{
                                                                                                                                                                                                                                                                                through > ApplicationException(string.Format("Couldn't parse XML: '{0}'; Contains BOM: {1}; Type: {2}.",
                                       🎜>        }
                        return result;                                            
        ///
        /// 序列化object对象为XML字符串
        ///

        public static string Serialize(object ObjectToSerialize)
        {
            string result = null ;
            try
            {
            XmlSerializer xmlSerializer = new XmlSerializer(ObjectToSerialize.GetType());

            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false));
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlSerializer.Serialize(xmlTextWriter, ObjectToSerialize);
                xmlTextWriter.Flush();
                xmlTextWriter.Close();
                UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                result= uTF8Encoding.GetString(memoryStream.ToArray());
            }
            }
            catch (Exception innerException)
            {
                throw new ApplicationException("Couldn't Serialize Object:" + ObjectToSerialize.GetType().Name, innerException);
            }
            return result;
        }
    }

要使用这个类需要添加以下引用
using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
下面我们用一个控制台程序来演示一下这个类是如何工作的。这里是程序的Main函数。
复制代码 代码如下:

static void Main(string[] args)
{
List Members = new List();
Member member1 = new Member { Name = "Marry" , Num = "001" };
Member member2 = new Member { Name = "John", Num = "002" };
Members.Add(member1);
Members.Add(member2);
                                Team team = new Team { Name = "Development",                 var xml = EncodeHelper. Serialized XML string
Console.ReadLine();
Team newTeam = EncodeHelper.Deserialize(xml, typeof(Team)) as Team;//Explicit type conversion is required during deserialization
       Console.WriteLine("Team Name:"+newTeam.Name);//Display the deserialized newTeam object
                                                           .WriteLine( "Member Num:" + member.Num);
Console.WriteLine("Member Name:" + member.Name);
}
Console.ReadLine();
}


After executing the Console.Write(xml) line of code, you can see the printed XML document.


Copy code
The code is as follows:
Development


;
                                                                   > < ;/Members>



is exactly the same as the example I gave at the beginning of the article.
The final deserialized newTeam object is printed like this.

Team Name:Development
Member Num:001
Member Name:Marry
Member Num:002
Member Name:John
Back to the Web where we started As an example of communication,
uses XML serialization and deserialization to transfer objects. We only need to serialize the objects that need to be transferred into XML strings, and use a hidden field to submit the form and that's it!
The receiver can then deserialize the received XML string into a preset object. The premise is that both parties must agree that the serialization and deserialization processes are consistent and the objects are the same.
Finally, let’s take a look at how to use some features to control the process of serialization and deserialization operations. Let’s change the starting class:



Copy the code
The code is as follows:


public class Member
{
[XmlElement("Member_Num")]
public string Num { get; set; } public string Name { get; set; } } [XmlRoot("Our_Team")] public class Team
{
[XmlIgnore] public string Name;
public List Members { get; set; }
}


Then we execute the console program just now again, and the serialization result becomes like this:
Copy the code The code is as follows:





;Name>Marry
                                                                 🎜>





The original root node Team becomes Our_Team, and the child node Num of Member becomes Member_Num, And the Name subnode of Team is ignored.
The visible feature XmlRoot can control the display and operation process of the root node, while XmlElement targets child nodes. If some members are marked XmlIgnore, they will be ignored during serialization and deserialization.
The specific content of these features can be viewed on MSDN, so I won’t go into details.
With this knowledge, it should be no longer difficult for you to transfer object data in the network. ^_^




http://www.bkjia.com/PHPjc/327539.htmlwww.bkjia.com

truehttp: //www.bkjia.com/PHPjc/327539.htmlTechArticleThis article mainly talks about the serialization and deserialization of XML and objects. And some simple serialization and deserialization methods will be attached for everyone to use. Let's say we have... in a web project
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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! How can I make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! Mar 15, 2024 pm 04:13 PM

1. How can you make money by publishing articles on Toutiao today? How to earn more income by publishing articles on Toutiao today! 1. Activate basic rights and interests: original articles can earn profits by advertising, and videos must be original in horizontal screen mode to earn profits. 2. Activate the rights of 100 fans: if the number of fans reaches 100 fans or above, you can get profits from micro headlines, original Q&amp;A creation and Q&amp;A. 3. Insist on original works: Original works include articles, micro headlines, questions, etc., and are required to be more than 300 words. Please note that if illegally plagiarized works are published as original works, credit points will be deducted, and even any profits will be deducted. 4. Verticality: When writing articles in professional fields, you cannot write articles across fields at will. You will not get appropriate recommendations, you will not be able to achieve the professionalism and refinement of your work, and it will be difficult to attract fans and readers. 5. Activity: high activity,

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

What is the difference between arrays and objects in PHP? What is the difference between arrays and objects in PHP? Apr 29, 2024 pm 02:39 PM

In PHP, an array is an ordered sequence, and elements are accessed by index; an object is an entity with properties and methods, created through the new keyword. Array access is via index, object access is via properties/methods. Array values ​​are passed and object references are passed.

How to use PHP functions to process XML data? How to use PHP functions to process XML data? May 05, 2024 am 09:15 AM

Use PHPXML functions to process XML data: Parse XML data: simplexml_load_file() and simplexml_load_string() load XML files or strings. Access XML data: Use the properties and methods of the SimpleXML object to obtain element names, attribute values, and subelements. Modify XML data: add new elements and attributes using the addChild() and addAttribute() methods. Serialized XML data: The asXML() method converts a SimpleXML object into an XML string. Practical example: parse product feed XML, extract product information, transform and store it into a database.

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles