Use C # to implement serialization and deserialization conversion between XML and object classes

Source: Internet
Author: User
Code snippets, code sharing, PHP code sharing, Java code sharing, Ruby code sharing, Python code sharing, HTML code sharing, CSS code sharing, SQL code sharing, and JavaScript code sharing
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 ;////// Xml serialization and deserialization ///Public class XmlUtil {# region deserialization ////// Deserialization //////Type///XML string///
 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 ;}}////// Deserialization ////////////
 Public static object Deserialize (Type type, Stream stream) {XmlSerializer xmldes = new XmlSerializer (type); return xmldes. Deserialize (stream);} # endregion # region serialization ////// Serialization //////Type///Object///
 Public static string Serializer (Type type, object obj) {MemoryStream Stream = new MemoryStream (); XmlSerializer xml = new XmlSerializer (type); try {// serialize 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}/* convert object to Xml */public class Student {public string Name {set; get;} public int Age {set; get ;}} Student stu1 = new Student () {Name = "okbase", Age = 10}; string xml = XmlUtil. serializer (typeof (Student), stu1); Console. write (xml);/* Convert Xml to object */Student stu2 = XmlUtil. deserialize (typeof (Student), xml) as Student; Console. write (string. format ("name: {0}, age: {1}", stu2.Name, stu2.Age )); /* DataTable conversion to Xml * // Generate a DataTable object for testing DataTable dt1 = new DataTable ("mytable"); // The DataTable name dt1.Columns must be specified. add ("Dosage", typeof (int); dt1.Columns. add ("Drug", typeof (string); dt1.Columns. add ("Patient", typeof (string); dt1.Columns. add ("Date", typeof (DateTime); // Add line dt1.Rows. add (25, "Indocin", "David", DateTime. now); dt1.Rows. add (50, "Enebrel", "Sam", DateTime. now); dt1.Rows. add (10, "Hydralazine", "0000FF", DateTime. now); dt1.Rows. add (21, "Combivent", "Janet", DateTime. now); dt1.Rows. add (100, "Dilantin", "meleni", DateTime. now); // serialized xml = XmlUtil. serializer (typeof (DataTable), dt1); Console. write (xml);/* Convert Xml to DataTable * // deserialize DataTable dt2 = XmlUtil. deserialize (typeof (DataTable), xml) as DataTable; // output the test result foreach (DataRow dr in dt2.Rows) {foreach (DataColumn col in dt2.Columns) {Console. write (dr [col]. toString () + "");} Console. write ("\ r \ n");}/* List to Xml * // Generate a List object for testing the List
 
  
List1 = new List
  
   
(3); list1.Add (new Student () {Name = "okbase", Age = 10}); list1.Add (new Student () {Name = "csdn ", age = 15}); // serialized xml = XmlUtil. serializer (typeof (List
   
    
), List1); Console. Write (xml);/* Convert Xml to List */List
    
     
List2 = XmlUtil. Deserialize (typeof (List
     
      
), Xml) as List
      
        ; Foreach (Student stu in list2) {Console. writeLine (stu. name + "," + stu. age. toString ();} protected void Page_Load (object sender, EventArgs e) {string strTest = @"
        
         
          
           
           
             ATVPDKIKX0DER
           B00K69WURQ 
           
           
           
             TBVPDKIKX0DER
           C00K69WURQ 
           
           
           
             KlVPDKIKX0DER
           D00K69WURQ 
           
          
         
       "; TextBox1.Text =" "; XmlDocument doc = new XmlDocument (); doc. loadXml (strTest); XmlElement root = doc. documentElement; // used to operate XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc. nameTable); nsmgr. addNamespace ("AB", "http://www.microsoft.com/schema/Products/2011-10-01"); XmlNodeList macthNodes = root. selectNodes ("// AB: Identifiers/AB: MarketplaceASIN", nsmgr); for (int I = 0; I <macthN Odes. Count; I ++) {// delete the generated namespace and generate standard XML. String matchNode = CleanXmlnsTag (macthNodes [I]. OuterXml); MarketplaceASIN ma = XmlUtil. Deserialize (typeof (MarketplaceASIN), matchNode) as MarketplaceASIN; if (ma! = Null) {Response. Write (ma. MarketplaceId + "---------" + ma. ASIN +"
       
") ;}}/ * Entity object */public class MarketplaceASIN {public string MarketplaceId {set; get;} public string ASIN {set; get ;}} protected string CleanXmlnsTag (string xml) {xml = xml. replace ("xmlns = \" http://www.microsoft.com/schema/Products/2011-10-01\ "", ""); return xml ;}

The preceding section describes how to use C # to implement serialization and deserialization conversion between XML and object classes. For more information, see other related articles in the first PHP community!

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.