


In-depth understanding: XML and object serialization and deserialization_PHP tutorial
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
public class Member
{
public string Num { get; set; }
public string Name { get; set; }
}
public class Team
{
public string Name;
Public List
}
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:
@model Team
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:
& 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.
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.
///
/// 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
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
;
> < ;/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
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 List
}
Then we execute the console program just now again, and the serialization result becomes like this:
;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

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

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

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



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&A creation and Q&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,

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.

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.

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.

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.

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.

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.

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
