Home  >  Article  >  Backend Development  >  In-depth understanding: XML and object serialization and deserialization_PHP tutorial

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

WBOY
WBOYOriginal
2016-07-21 15:07:24967browse

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:
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