使用C#实现实体类和XML相互转换

一、实体类转换成XML

将实体类转换成XML需要使用XmlSerializer类的Serialize方法,将实体类序列化

public static string XmlSerialize<T>(T obj)
{
       using (StringWriter sw = new StringWriter())
       {
             Type t= obj.GetType();             
             XmlSerializer serializer = new XmlSerializer(obj.GetType());
             serializer.Serialize(sw, obj);
             sw.Close();
             return sw.ToString();
        }
}

示例:

1、定义实体类

 1     [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
 2     [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
 3     public class Request
 4     {
 5 
 6         public string System { get; set; }
 7         public string SecurityCode { get; set; }
 8         public PatientBasicInfo PatientInfo { get; set; }      
 9     }
10 
11     /// <remarks/>
12     [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
13     public partial class PatientBasicInfo
14     {
15         public string PatientNo { get; set; }
16         public string PatientName { get; set; }
17         public string Phoneticize { get; set; }
18         public string Sex { get; set; }
19         public string Birth { get; set; }
20         public string BirthPlace { get; set; }
21         public string Country { get; set; }
22         public string Nation { get; set; }
23         public string IDNumber { get; set; }
24         public string SecurityNo { get; set; }
25         public string Workunits { get; set; }
26         public string Address { get; set; }
27         public string ZIPCode { get; set; }
28         public string Phone { get; set; }
29         public string ContactPerson { get; set; }
30         public string ContactShip { get; set; }
31         public string ContactPersonAdd { get; set; }
32         public string ContactPersonPhone { get; set; }
33         public string OperationCode { get; set; }
34         public string OperationName { get; set; }
35         public string OperationTime { get; set; }
36         public string CardNo { get; set; }
37         public string ChangeType { get; set; }
38 
39     }

2、给实体类赋值,并通过序列化将实体类转换成XML格式的字符串

 1 Request patientIn = new Request();
 2             patientIn.System = "HIS";
 3             patientIn.SecurityCode = "HIS5";
 4 
 5             PatientBasicInfo basicInfo = new PatientBasicInfo();
 6             basicInfo.PatientNo = "1234";
 7             basicInfo.PatientName = "测试";
 8             basicInfo.Phoneticize = "";
 9             basicInfo.Sex = "1";
10             basicInfo.Birth = "";
11             basicInfo.BirthPlace = "";
12             basicInfo.Country = "";
13             basicInfo.Nation = "";
14             basicInfo.IDNumber = "";
15             basicInfo.SecurityNo = "";
16             basicInfo.Workunits = "";
17             basicInfo.Address = "";
18             basicInfo.ZIPCode = "";
19             basicInfo.Phone = "";
20             basicInfo.ContactShip = "";
21             basicInfo.ContactPersonPhone = "";
22             basicInfo.ContactPersonAdd = "";
23             basicInfo.ContactPerson = "";
24             basicInfo.ChangeType = "";
25             basicInfo.CardNo = "";
26             basicInfo.OperationCode = "";
27             basicInfo.OperationName = "";
28             basicInfo.OperationTime = "";
29 
30             patientIn.PatientInfo = basicInfo;
31 
32             //序列化
33             string strxml = XmlSerializeHelper.XmlSerialize<Request>(patientIn);

3、生成的XML实例

 1 <?xml version="1.0" encoding="utf-16"?>
 2 <Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
 3   <System>HIS</System>
 4   <SecurityCode>HIS5</SecurityCode>
 5   <PatientInfo>
 6     <PatientNo>1234</PatientNo>
 7     <PatientName>测试</PatientName>
 8     <Phoneticize />
 9     <Sex>1</Sex>
10     <Birth />
11     <BirthPlace />
12     <Country />
13     <Nation />
14     <IDNumber />
15     <SecurityNo />
16     <Workunits />
17     <Address />
18     <ZIPCode />
19     <Phone />
20     <ContactPerson />
21     <ContactShip />
22     <ContactPersonAdd />
23     <ContactPersonPhone />
24     <OperationCode />
25     <OperationName />
26     <OperationTime />
27     <CardNo />
28     <ChangeType />
29   </PatientInfo>
30 </Request>

二、将XML转换成实体类

把XML转换成相应的实体类,需要使用到XmlSerializer类的Deserialize方法,将XML进行反序列化。

 1 public static T DESerializer<T>(string strXML) where T:class
 2 {
 3      try
 4     {
 5             using (StringReader sr = new StringReader(strXML))
 6            {
 7                 XmlSerializer serializer = new XmlSerializer(typeof(T));
 8                 return serializer.Deserialize(sr) as T;
 9            }
10      }
11      catch (Exception ex)
12      {
13             return null;
14      }
15 }

示例:

将上例中序列化后的XML反序列化成实体类

1 //反序列化
2 Request r = XmlSerializeHelper.DESerializer<Request>(strxml);

 三、将DataTable转换成XML

 1  //将DataTable转换成XML
 2 DataTable dt = new DataTable("MyTable");
 3 //添加列
 4 dt.Columns.Add("Id", typeof(int));
 5 dt.Columns.Add("Name", typeof(string));
 6 dt.Columns.Add("Sex", typeof(char));
 7 //添加行
 8 dt.Rows.Add(1, "小明", '1');
 9 dt.Rows.Add(2, "小红", '2');
10 dt.Rows.Add(3, "小王", '2');
11 dt.Rows.Add(4, "测试", '2');
12 //序列化,将DataTable转换成XML格式的字符串
13 string strXML = XmlSerializeHelper.XmlSerialize <DataTable> (dt);

四、将XML转换成DataTable

1 //反序列化,将XML转换成字符串
2 DataTable dtNew=  XmlSerializeHelper.DESerializer<DataTable>(strXML);

五、将List集合转换成XML

/// <summary>
/// 测试类
/// </summary>
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public char Sex { get; set; }
    public int Age { get; set; }
}

//测试集合
List<Student> list = new List<Student>()
{
        new Student(){Id=1,Name="小红",Sex='2',Age=20},
        new Student(){Id=2,Name="小明",Sex='1',Age=22},
        new Student(){Id=3,Name="小王",Sex='1',Age=19},
        new Student(){Id=4,Name="测试",Sex='2',Age=23}
};
//序列化
string strXML = XmlSerializeHelper.XmlSerialize<List<Student>>(list);

六、将XML转换成集合

使用上面例子中集合转换成的XML进行反序列化。

1 //反序列化
2 List<Student> listStu = XmlSerializeHelper.DESerializer<List<Student>>(strXML);

 

posted @ 2017-03-07 10:59  .NET开发菜鸟  阅读(40585)  评论(1编辑  收藏  举报