Share C # code for XML and entity serialization and deserialization

Source: Internet
Author: User

This article will share with you how to use C # To implement XML and entity serialization and deserialization functions.

Class provides us with our own object serialize and deserialize XML methods, which can be serialized:
Public read/write fields or attributes of public classes
Xmlelement object
Xmlnode object
DataSet object
Class that implements icollection or ienumerable

This class has a design requirement in the design:
The class to be serialized must provide a constructor with null parameters. Otherwise, an exception occurs during runtime.

Objects and XML conversion may be used in many aspects during the development process. A common class is provided to support generic types.

Code [http://www.xueit.com]
/// <Summary> /// serialization help class /// </Summary> public class shelper {// <summary> // object to XML ----- generic type // // </Summary> /// <typeparam name = "T"> </typeparam> /// <Param name = "OBJ"> </param> // <returns> </returns> Public static string savexmlfromobj <t> (t obj) {If (OBJ = NULL) return NULL; xmlserializer serializer = new xmlserializer (typeof (t); memorystream stream = new memorystream (); xmltextwriter xtw = N EW xmltextwriter (stream, encoding. utf8); xtw. formatting = formatting. indented; try {serializer. serialize (stream, OBJ);} catch {return NULL;} stream. position = 0; string returnstr = string. empty; using (streamreader sr = new streamreader (stream, encoding. utf8) {string line = ""; while (line = sr. readline ())! = NULL) {returnstr = line;} return returnstr ;} /// <summary> /// XML to deserialize to object ---- support generic type /// </Summary> /// <typeparam name = "T"> </typeparam> /// <Param name = "data"> </param> /// <returns> </returns> Public static t loadobjfromxml <t> (string data) {using (memorystream stream = new memorystream () {using (streamwriter Sw = new streamwriter (stream, encoding. utf8) {SW. write (data); Sw. flush (); stream. seek (0, seekorigin. begin); xmlserializer serializer = new xmlserializer (typeof (t); try {return (t) serializer. deserialize (Stream);} catch {return default (t );}}}}}

This class provides two methods: one is the method from the entity to the XML string returned, and the other is the method of loading the XML string into the object entity. Next let's take a look at how this class is used.

First, two classes of user and users are created. user tests the serialization and deserialization of an object, and users tests the serialization and deserialization of a list set. Note that both classes are labeled with the [serializable] Feature and provide constructors with null parameters.

[Serializable]
2 public class User
3 {
4 public int ID { get; set; }
5 public string Name { get; set; }
6 public string Add { get; set; }
7 public int Age { get; set; }
8
9
10 public User()
11 {
12 this.ID = default(int);
13 this.Name = default(string);
14 this.Add = default(string);
15 this.Age = default(int);
16 }
17
18 }
 [Serializable]
public class Users
{
public List<User> Datas { get; set; }
public Users()
{
this.Datas=new List<User>();
}
}

Next, we will create a page default. aspx. on this page, we test serialization and provide two buttons and two textbox to display serialization of a single object and serialization of a list set respectively.

<Form ID = "form1" runat = "server">
<Div>
<Asp: button id = "button1" runat = "server" text = "one object serialization"
Onclick = "button#click"/>
<Br/>
<Asp: textbox id = "textbox1" runat = "server" width = "100%" Height = "200"> </ASP: textbox> <br/>
<Asp: button id = "button2" runat = "server" text = "serialization of multiple objects"
Onclick = "button2_click"/> <br/>
<Asp: textbox id = "textbox2" runat = "server" width = "100%" Height = "200"> </ASP: textbox> <br/>
</Div>
</Form>

Implementation of background code:

/// <Summary>
/// Serialize an object
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Protected void button#click (Object sender, eventargs E)
{
User user = new user () {id = 1001, name = "", add = "Beijing", age = 21 };
VaR STR = shelper. savexmlfromobj <user> (User );
This. textbox1.text = STR;
}

/// <Summary>
/// Serialize multiple objects
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "E"> </param>
Protected void button2_click (Object sender, eventargs E)
{
Users users = new users ();
User user = new user () {id = 1001, name = "", add = "Beijing", age = 21 };
Users. datas. Add (User );
Users. datas. Add (User );
Users. datas. Add (User );

VaR STR = shelper. savexmlfromobj <users> (users );
This. textbox2.text = STR;
}

The serialization result is as follows:

Single Object:

Code [http://www.xueit.com]
<? XML version = "1.0"?> <User xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema"> <ID> 1001 </ID> <Name> JOHN </Name> <add> Beijing </Add> <age> 21 </age> </ user> list set: <? XML version = "1.0"?> <Users xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: XSD = "http://www.w3.org/2001/XMLSchema"> <datas> <user> <ID> 1001 </ID> <Name> JOHN </Name> <add> Beijing </Add> <age> 21 </age> </user> <ID> 1001 </ID> <Name> JOHN </Name> <add> Beijing </Add> <age> 21 </age> </user> <ID> 1001 </ID> <Name> JOHN </Name> <add> Beijing </Add> <age> 21 </ age> </user> </datas> </users>

Next we will test deserialization:

First, create a WebService and write two test methods:

[Webmethod]
Public String getobjfromxml (string data)
{
VaR OBJ = shelper. loadobjfromxml <user> (data );
If (OBJ! = NULL)
{Return obj. Name ;}
Else {return "incoming data error ";}
}

[Webmethod]
Public String getobjsfromxml (string data)
{
VaR OBJ = shelper. loadobjfromxml <users> (data );
If (OBJ! = NULL)
{
String returnstr = "";
Foreach (User user in OBJ. datas)
{
Returnstr + = user. Name + "\ n ";
}
Return returnstr;
}
Else {return "incoming data error ";}
}

Compile and run the program. We can use the serialized string to paste the parameter value location to test the deserialization method. We will not detail it here. If you are interested, you can run the instance code.

Reprinted: http://www.xueit.com/cshare/show-9006-3.aspx

Sample Code: http://files.cnblogs.com/Clivia/SerializerHelper.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.