zoukankan      html  css  js  c++  java
  • c# XML和实体类之间相互转换(序列化和反序列化)

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.IO;
      6 using System.Data;
      7 using System.Xml;
      8 using System.Xml.Serialization;
      9  
     10 /// <summary>
     11 /// Xml序列化与反序列化
     12 /// </summary>
     13 public class XmlUtil
     14 {
     15     #region 反序列化
     16     /// <summary>
     17     /// 反序列化
     18     /// </summary>
     19     /// <param name="type">类型</param>
     20     /// <param name="xml">XML字符串</param>
     21     /// <returns></returns>
     22     public static object Deserialize(Type type, string xml)
     23     {
     24         try
     25         {
     26             using (StringReader sr = new StringReader(xml))
     27             {
     28                 XmlSerializer xmldes = new XmlSerializer(type);
     29                 return xmldes.Deserialize(sr);
     30             }
     31         }
     32         catch (Exception e)
     33         {
     34  
     35             return null;
     36         }
     37     }
     38     /// <summary>
     39     /// 反序列化
     40     /// </summary>
     41     /// <param name="type"></param>
     42     /// <param name="xml"></param>
     43     /// <returns></returns>
     44     public static object Deserialize(Type type, Stream stream)
     45     {
     46         XmlSerializer xmldes = new XmlSerializer(type);
     47         return xmldes.Deserialize(stream);
     48     }
     49     #endregion
     50  
     51     #region 序列化
     52     /// <summary>
     53     /// 序列化
     54     /// </summary>
     55     /// <param name="type">类型</param>
     56     /// <param name="obj">对象</param>
     57     /// <returns></returns>
     58     public static string Serializer(Type type, object obj)
     59     {
     60         MemoryStream Stream = new MemoryStream();
     61         XmlSerializer xml = new XmlSerializer(type);
     62         try
     63         {
     64             //序列化对象
     65             xml.Serialize(Stream, obj);
     66         }
     67         catch (InvalidOperationException)
     68         {
     69             throw;
     70         }
     71         Stream.Position = 0;
     72         StreamReader sr = new StreamReader(Stream);
     73         string str = sr.ReadToEnd();
     74          
     75         sr.Dispose();
     76         Stream.Dispose();
     77  
     78         return str;
     79     }
     80  
     81     #endregion
     82 }
     83 下面是测试代码:
     84  
     85 1. 实体对象转换到Xml
     86  
     87 1
     88 2
     89 3
     90 4
     91 5
     92 6
     93 7
     94 8
     95 9
     96 public class Student
     97 {
     98     public string Name { set; get; }
     99     public int Age { set; get; }
    100 }
    101  
    102 Student stu1 = new Student() { Name = "okbase", Age = 10 };
    103 string xml = XmlUtil.Serializer(typeof(Student), stu1);
    104 Console.Write(xml);
    105 2. Xml转换到实体对象
    106  
    107 1
    108 2
    109 Student stu2 = XmlUtil.Deserialize(typeof(Student), xml) as Student;
    110 Console.Write(string.Format("名字:{0},年龄:{1}", stu2.Name, stu2.Age));
    111 3. DataTable转换到Xml
    112  
    113 1
    114 2
    115 3
    116 4
    117 5
    118 6
    119 7
    120 8
    121 9
    122 10
    123 11
    124 12
    125 13
    126 14
    127 15
    128 16
    129 17
    130 18
    131 // 生成DataTable对象用于测试
    132 DataTable dt1 = new DataTable("mytable");   // 必须指明DataTable名称
    133  
    134 dt1.Columns.Add("Dosage", typeof(int));
    135 dt1.Columns.Add("Drug", typeof(string));
    136 dt1.Columns.Add("Patient", typeof(string));
    137 dt1.Columns.Add("Date", typeof(DateTime));
    138  
    139 // 添加行
    140 dt1.Rows.Add(25, "Indocin", "David", DateTime.Now);
    141 dt1.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    142 dt1.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    143 dt1.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    144 dt1.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
    145  
    146 // 序列化
    147 xml = XmlUtil.Serializer(typeof(DataTable), dt1);
    148 Console.Write(xml);
    149 4. Xml转换到DataTable
    150  
    151 1
    152 2
    153 3
    154 4
    155 5
    156 6
    157 7
    158 8
    159 9
    160 10
    161 11
    162 12
    163 13
    164 // 反序列化
    165 DataTable dt2 = XmlUtil.Deserialize(typeof(DataTable), xml) as DataTable;
    166  
    167 // 输出测试结果
    168 foreach (DataRow dr in dt2.Rows)
    169 {
    170     foreach (DataColumn col in dt2.Columns)
    171     {
    172         Console.Write(dr[col].ToString() + " ");
    173     }
    174  
    175     Console.Write("
    ");
    176 }
    177 5. List转换到Xml
    178  
    179 1
    180 2
    181 3
    182 4
    183 5
    184 6
    185 7
    186 8
    187 // 生成List对象用于测试
    188 List<Student> list1 = new List<Student>(3);
    189  
    190 list1.Add(new Student() { Name = "okbase", Age = 10 });
    191 list1.Add(new Student() { Name = "csdn", Age = 15 });
    192 // 序列化
    193 xml = XmlUtil.Serializer(typeof(List<Student>), list1);
    194 Console.Write(xml);
    195 6. Xml转换到List
    196  
    197 1
    198 2
    199 3
    200 4
    201 5
    202 List<Student> list2 = XmlUtil.Deserialize(typeof(List<Student>), xml) as List<Student>;
    203 foreach (Student stu in list2)
    204 {
    205     Console.WriteLine(stu.Name + "," + stu.Age.ToString());
    206 }
    207 从代码可以看到,千变万化不离其宗!
  • 相关阅读:
    Method "goodsList" has already been defined as a data property
    mac安装淘宝淘宝镜像失败
    webstrom git配置设置时右侧没有内容 select configuration element in the tree to edit its setting
    vue下标获取数据时候,页面报错
    透明度全兼容
    clipboard冲突mui.css,移动端实现复制粘贴
    Vue价格四舍五入保留两位和直接取两位
    实习大总结
    day33
    day31
  • 原文地址:https://www.cnblogs.com/allenzhang/p/5756495.html
Copyright © 2011-2022 走看看