C#實體類與XML相互轉換

一、實體類與XML相互轉換spa

將實體類轉換成XML須要使用XmlSerializer類的Serialize方法,將實體類序列化。xml

把XML轉換成相應的實體類,須要使用到XmlSerializer類的Deserialize方法,將XML進行反序列化。對象

建立XML序列化公共處理類(XmlSerializeHelper.cs)element

using System;
using System.IO;
using System.Xml.Serialization;

/// <summary>
/// XML序列化公共處理類
/// </summary>
public static class XmlSerializeHelper
{
/// <summary>
/// 將實體對象轉換成XML
/// </summary>
/// <typeparam name="T">實體類型</typeparam>
/// <param name="obj">實體對象</param>
public static string XmlSerialize<T>(T obj)
{
try
{
using (StringWriter sw = new StringWriter())
{
Type t = obj.GetType();
XmlSerializer serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(sw, obj);
sw.Close();
return sw.ToString();
}
}
catch (Exception ex)
{
throw new Exception("將實體對象轉換成XML異常", ex);
}
}

/// <summary>
/// 將XML轉換成實體對象
/// </summary>
/// <typeparam name="T">實體類型</typeparam>
/// <param name="strXML">XML</param>
public static T DESerializer<T>(string strXML) where T : class
{
try
{
using (StringReader sr = new StringReader(strXML))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return serializer.Deserialize(sr) as T;
}
}
catch (Exception ex)
{
throw new Exception("將XML轉換成實體對象異常", ex);
}
}
}
建立用戶信息類,用於示例使用。get

/// <summary>
/// 用戶信息類
/// </summary>
public class UserInfo
{
/// <summary>
/// 編號
/// </summary>
public int ID { get; set; }

/// <summary>
/// 名稱
/// </summary>
public string Name { get; set; }

/// <summary>
/// 建立時間
/// </summary>
public DateTime? CreateTime { get; set; }
}
1.1 示例1:將List與XML相互轉換string

/// <summary>
/// 將List與XML相互轉換
/// </summary>
public static void ListToXmlTest()
{
//獲取用戶列表
List<UserInfo> userList = GetUserList();

//將實體對象轉換成XML
string xmlResult = XmlSerializeHelper.XmlSerialize(userList);

//將XML轉換成實體對象
List<UserInfo> deResult = XmlSerializeHelper.DESerializer<List<UserInfo>>(xmlResult);
}

/// <summary>
/// 獲取用戶信息列表
/// </summary>
public static List<UserInfo> GetUserList()
{
List<UserInfo> userList = new List<UserInfo>();
userList.Add(new UserInfo() { ID = 1, Name = "張三", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "李四", CreateTime = DateTime.Now });
userList.Add(new UserInfo() { ID = 2, Name = "王五" });
return userList;
}
XML結果:it

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<UserInfo>
<ID>1</ID>
<Name>張三</Name>
<CreateTime>2018-10-04T15:59:53.7761027+08:00</CreateTime>
</UserInfo>
<UserInfo>
<ID>2</ID>
<Name>李四</Name>
<CreateTime>2018-10-04T15:59:54.9571044+08:00</CreateTime>
</UserInfo>
<UserInfo>
<ID>2</ID>
<Name>王五</Name>
<CreateTime xsi:nil="true" />
</UserInfo>
</ArrayOfUserInfo>
1.2 示例2:將DataTable與XML相互轉換io

/// <summary>
/// 將DataTable與XML相互轉換
/// </summary>
public static void DataTableToXmlTest()
{
//建立DataTable對象
DataTable dt = CreateDataTable();

//將DataTable轉換成XML
string xmlResult = XmlSerializeHelper.XmlSerialize(dt);

//將XML轉換成DataTable
DataTable deResult = XmlSerializeHelper.DESerializer<DataTable>(xmlResult);
}

/// <summary>
/// 建立DataTable對象
/// </summary>
public static DataTable CreateDataTable()
{
//建立DataTable
DataTable dt = new DataTable("NewDt");

//建立自增加的ID列
DataColumn dc = dt.Columns.Add("ID", Type.GetType("System.Int32"));
dt.Columns.Add(new DataColumn("Name", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("CreateTime", Type.GetType("System.DateTime")));

//建立數據
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["Name"] = "張三";
dr["CreateTime"] = DateTime.Now;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["ID"] = 2;
dr["Name"] = "李四";
dr["CreateTime"] = DateTime.Now;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["ID"] = 3;
dr["Name"] = "王五";
dr["CreateTime"] = DateTime.Now;
dt.Rows.Add(dr);

return dt;
}
XML結果:class

<?xml version="1.0" encoding="utf-16"?>
<DataTable>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="NewDt" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="NewDt">
<xs:complexType>
<xs:sequence>
<xs:element name="ID" type="xs:int" minOccurs="0" />
<xs:element name="Name" type="xs:string" minOccurs="0" />
<xs:element name="CreateTime" type="xs:dateTime" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement>
<NewDt diffgr:id="NewDt1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
<ID>1</ID>
<Name>張三</Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
</NewDt>
<NewDt diffgr:id="NewDt2" msdata:rowOrder="1" diffgr:hasChanges="inserted">
<ID>2</ID>
<Name>李四</Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
</NewDt>
<NewDt diffgr:id="NewDt3" msdata:rowOrder="2" diffgr:hasChanges="inserted">
<ID>3</ID>
<Name>王五</Name>
<CreateTime>2018-10-04T16:06:10.8004082+08:00</CreateTime>
</NewDt>
</DocumentElement>
</diffgr:diffgram>
</DataTable>
二、序列化經常使用Attribute講解說明date

[XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=false)]     // 當該類爲Xml根節點時,以此爲根節點名稱。
public class City

[XmlAttribute("AreaName")]    // 表現爲Xml節點屬性。<... AreaName="..."/>
public string Name

[XmlElementAttribute("AreaId", IsNullable = false)]    // 表現爲Xml節點。<AreaId>...</AreaId>
public string Id

[XmlArrayAttribute("Areas")]    // 表現爲Xml層次結構,根爲Areas,其所屬的每一個該集合節點元素名爲類名。<Areas><Area ... /><Area ... /></Areas>
public Area[] Areas

[XmlElementAttribute("Area", IsNullable = false)]    // 表現爲水平結構的Xml節點。<Area ... /><Area ... />...
public Area[] Areas

[XmlIgnoreAttribute]    // 忽略該元素的序列化。

把這些屬性與model類的相關屬性,配合使用,就能夠自由設置相關XML的具體格式了。

綜合示例:將班級信息序列化成XML

示例要求:

(1)每一個XML節點以「My」開頭。

(2)班級ID和學生ID字段以XML節點屬性表現,其它字段以XML節點的形式表現。

(3)因爲學生的郵箱涉及敏感信息,因此不參與序列化。

2.1 建立班級信息類(ClassInfo.cs)

using System.Collections.Generic;
using System.Xml.Serialization;

/// <summary>
/// 班級信息類
/// </summary>
[XmlRootAttribute("MyClassInfo", Namespace = "ABC_123", IsNullable = false)]
public class ClassInfo
{
/// <summary>
/// 班級ID
/// </summary>
[XmlAttribute("MyClassID")]
public int ClassID { get; set; }

/// <summary>
/// 班級名稱
/// </summary>
[XmlElementAttribute("MyClassName", IsNullable = false)]
public string ClassName { get; set; }

/// <summary>
/// 班長人
/// </summary>
[XmlElementAttribute("MyTeacher", IsNullable = false)]
public string Teacher { get; set; }

/// <summary>
/// 學生列表
/// </summary>
[XmlArrayAttribute("MyStudents")]
public List<Student> StudentList { get; set; }
}
2.2 建立學生信息類(Student.cs)

using System.Xml.Serialization;

/// <summary>
/// 學生信息類
/// </summary>
[XmlRootAttribute("MyStudent", IsNullable = false)]
public class Student
{
/// <summary>
/// 學生ID
/// </summary>
[XmlAttribute("MyStuID")]
public int StuID { get; set; }

/// <summary>
/// 學生名稱
/// </summary>
[XmlElementAttribute("MyStuName", IsNullable = false)]
public string StuName { get; set; }

/// <summary>
/// 性別
/// </summary>
[XmlElementAttribute("MySex", IsNullable = false)]
public string Sex { get; set; }

/// <summary>
/// 郵箱
/// </summary>
[XmlIgnoreAttribute]
public string Email { get; set; }
}
2.3 將班級信息轉換成XML

/// <summary>
/// 將班級信息轉換成XML
/// </summary>
public static void ClassInfoToXml()
{
//獲取班級信息
ClassInfo classInfo = GetClassInfo();

//將班級信息轉換成XML
string classXml = XmlSerializeHelper.XmlSerialize(classInfo);
}

/// <summary>
/// 獲取班級信息
/// </summary>
public static ClassInfo GetClassInfo()
{
//建立班級信息
ClassInfo classInfo = new ClassInfo();
classInfo.ClassID = 1;
classInfo.ClassName = "高一(5)班";
classInfo.Teacher = "李老師";

//建立學生列表
List<Student> studentList = new List<Student>();
studentList.Add(new Student() { StuID = 1, StuName = "張三", Sex = "男", Email = "zhangsan@mail.com" });
studentList.Add(new Student() { StuID = 2, StuName = "李四", Sex = "女", Email = "lisi@mail.com" });
studentList.Add(new Student() { StuID = 3, StuName = "王五", Sex = "男", Email = "wangwu@mail.com" });
classInfo.StudentList = studentList;

return classInfo;
}
XML結果:

<?xml version="1.0" encoding="utf-16"?><MyClassInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" MyClassID="1" xmlns="ABC_123"> <MyClassName>高一(5)班</MyClassName> <MyTeacher>李老師</MyTeacher> <MyStudents> <Student MyStuID="1"> <MyStuName>張三</MyStuName> <MySex>男</MySex> </Student> <Student MyStuID="2"> <MyStuName>李四</MyStuName> <MySex>女</MySex> </Student> <Student MyStuID="3"> <MyStuName>王五</MyStuName> <MySex>男</MySex> </Student> </MyStudents></MyClassInfo> 

相關文章
相關標籤/搜索