C#中实体类与XML相互转换方式

Ula ·
更新时间:2024-11-13
· 1578 次阅读

目录

1、实体类与XML相互转换

1.1 示例1:将List与XML相互转换

1.2 示例2:将DataTable与XML相互转换

2、序列化常用Attribute讲解说明

综合示例:将班级信息序列化成XML

2.1 创建班级信息类(ClassInfo.cs)

2.2 创建学生信息类(Student.cs)

2.3 将班级信息转换成XML

总结

1、实体类与XML相互转换

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

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

创建XML序列化公共处理类(XmlSerializeHelper.cs)

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); } } }

创建用户信息类,用于示例使用。

/// <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相互转换 /// <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结果:

<?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相互转换 /// <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结果:

<?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> 2、序列化常用Attribute讲解说明 [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> 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。 



XML C# 实体 实体类

需要 登录 后方可回复, 如果你还没有账号请 注册新账号