


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

深入了解HTTP状态码100:它代表什么意思?HTTP协议是现代互联网应用中最为常用的协议之一,它定义了浏览器和Web服务器之间进行通信所需的标准规范。在HTTP请求和响应的过程中,服务器会向浏览器返回各种类型的状态码,以反映请求的处理情况。其中,HTTP状态码100是一种特殊的状态码,用来表示"继续"。HTTP状态码由三位数字组成,每个状态码都有特定的含义

深入理解Linux管道的使用方法在Linux操作系统中,管道是一种非常有用的功能,能够将一个命令的输出作为另一个命令的输入,从而方便地实现各种复杂的数据处理和操作。深入理解Linux管道的使用方法对于系统管理员和开发人员来说非常重要。本文将介绍管道的基本概念,并通过具体的代码示例来展示如何使用Linux管道进行数据处理和操作。1.管道的基本概念在Linux

如何正确理解PHP中的值传递方式PHP是一种广泛应用于Web开发的脚本语言,而在PHP中的参数传递方式主要有值传递和引用传递两种。而理解PHP中的值传递方式对于编写高效的代码至关重要。本文将详细讨论PHP中的值传递方式,并通过具体的代码示例来帮助读者更好地理解。值传递方式的基本概念值传递是指将变量的值复制一份传递给函数或方法,在函数内部对该值的操作不会影响到

深入理解Go语言文档中的strings.Split函数,需要具体代码示例在Go语言中,字符串操作是非常常见的需求。其中,strings包是Go语言提供的一个标准包,提供了丰富的字符串处理函数。其中,strings.Split函数是其中一个常用的函数,它的作用是根据指定的分隔符将一个字符串拆分成一个字符串切片。在正式深入探讨strings.Split函数之前,

Linuxldconfig是一个用于动态链接库管理的工具,可以帮助系统在运行时找到并加载共享库。它主要用于更新系统的动态链接器运行时连接库缓存,以保证程序可以正确链接到共享库。ldconfig主要用于两个方面:一是添加、删除共享库路径,并更新相关信息到配置文件中;二是根据配置文件中的路径重新生成动态连接库链接器的缓存。接下来将介绍如何使用ldconf

随着现代Web应用程序的复杂性不断增加,代码逻辑也变得越来越复杂。为了解决这个问题,中间件在现代Web开发中变得越来越流行。ThinkPHP6是一个流行的PHP框架,它也支持中间件。在这篇文章中,我们将讨论ThinkPHP6中间件的基础知识和实际使用。什么是中间件?在Web开发中,中间件是指对HTTP请求和响应进行处理的一种方式。当客户端发送请求至服务器时,

MySQL中的布尔类型是一种非常实用的数据类型,它用于存储逻辑值,只能取两种值:TRUE或FALSE。在MySQL中,布尔类型也被称为BOOL或BOOLEAN,可以用TINYINT(1)来表示。在本文中,我们将深入探讨MySQL中布尔类型的定义、用法以及具体的代码示例。首先,让我们来看一下在MySQL中如何定义一个布尔类型的列:CREATETABLEus

Go语言是一种简洁而强大的编程语言,在许多方面都具有独特的设计和特点。其中一个让人印象深刻的特性就是range关键字,它被用于迭代数组、切片、映射和通道等数据结构。range的灵活性和便捷性使得遍历复杂数据结构变得简单,但其工作原理却有许多人感到困惑。本文将深入浅出地解释range的工作原理,并通过具体代码示例来帮助读者更好地理解。首先,让我们看一个简单的例


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

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.