C # XML and entity classes convert to and from each other (serialization and deserialization)

Source: Internet
Author: User

XML is transformed between the entity class, Datatable,list, and the following is the Xmlutil class, which comes from the network and is slightly modified.

Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using System.Data; Using system.xml;using System.Xml.Serialization; <summary>///serialization and deserialization of XML//</summary>public class xmlutil{#region deserialization///<summary>// Deserialization///</summary>//<param name= "type" > Type </param>//<param name= "xml" >xml string </pa        ram>//<returns></returns> public static object deserialize (type type, string xml) {try  {using (StringReader sr = new StringReader (XML)) {XmlSerializer xmldes = new                XmlSerializer (type); Return xmldes.            Deserialize (SR);        }} catch (Exception e) {return null; }}///<summary>//deserialization///</summary>//<param name= "type" ></param>///&L T;param name= "xml" ></param>///<returns></retUrns> public static object deserialize (type type, stream stream) {XmlSerializer xmldes = new Xmlserialize        R (type); Return xmldes.    Deserialize (stream); } #endregion #region Serialization///<summary>//serialization///</summary>//<param name= "type" > Type </param>//<param name= "obj" > Objects </param>//<returns></returns> public static S        Tring Serializer (Type type, Object obj) {MemoryStream Stream = new MemoryStream ();        XmlSerializer XML = new XmlSerializer (type); try {//serialization of the object XML.        Serialize (Stream, obj);        } catch (InvalidOperationException) {throw;        } stream.position = 0;        StreamReader sr = new StreamReader (Stream); String str = Sr.                 ReadToEnd (); Sr.        Dispose ();         Stream.dispose ();    return str; } #endregion}

  

Here is the test code:

1. Converting entity objects to XML

1  Public classStudent2 {3      Public stringName {Set;Get; }4      Public intAge {Set;Get; }5 }6  7Student STU1 =NewStudent () {Name ="Okbase", age =Ten };8 stringXML = Xmlutil.serializer (typeof(Student), STU1);9Console.Write (XML);

2. Converting XML to entity objects

1 Student stu2 = xmlutil.deserialize (typeof as Student; 2 console.write (string. Format (" name: {0}, Age: {1}", STU2. Name, STU2. Age));

3. DataTable conversion to XML

1 //generate a DataTable object for testing2DataTable DT1 =NewDataTable ("mytable");//The DataTable name must be specified3  4Dt1. Columns.Add ("dosage",typeof(int));5Dt1. Columns.Add ("Drug",typeof(string));6Dt1. Columns.Add ("Patient",typeof(string));7Dt1. Columns.Add ("Date",typeof(DateTime));8  9 //Adding RowsTenDt1. Rows.Add ( -,"indocin","David", DateTime.Now); OneDt1. Rows.Add ( -,"Enebrel","Sam", DateTime.Now); ADt1. Rows.Add (Ten,"hydralazine","Christoff", DateTime.Now); -Dt1. Rows.Add ( +,"combivent","Janet", DateTime.Now); -Dt1. Rows.Add ( -,"Dilantin","Melanie", DateTime.Now); the   - //Serialization of -XML = Xmlutil.serializer (typeof(DataTable), DT1); -Console.Write (XML);

4. XML conversion to DataTable

1 //deserialization2DataTable DT2 = Xmlutil.deserialize (typeof(DataTable), XML) asDataTable;3  4 //Output Test Results5 foreach(DataRow DrinchDT2. Rows)6 {7     foreach(DataColumn ColinchDT2. Columns)8     {9Console.Write (Dr[col]. ToString () +" ");Ten     } One   AConsole.Write ("\ r \ n"); -}

5. list conversion to XML

1 //generate a list object for testing2List<student> List1 =NewList<student> (3);3  4List1. ADD (NewStudent () {Name ="Okbase", age =Ten });5List1. ADD (NewStudent () {Name ="csdn", age = the });6 //Serialization of7XML = Xmlutil.serializer (typeof(list<student>), list1);8Console.Write (XML);

6. Convert XML to List

1 list<student> list2 = xmlutil.deserialize (typeof as list<student>; 2 foreach inch list2) 3 {4     " , " + stu. Age.tostring ()); 5 }

C # XML and entity classes convert to and from each other (serialization and deserialization)

Related Article

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.