C#实体类与XML相互转换
2021-02-02 12:14
标签:式表 uid 形式 array where ota exception choice 学生 1、实体类与XML相互转换 将实体类转换成XML需要使用XmlSerializer类的Serialize方法,将实体类序列化。 把XML转换成相应的实体类,需要使用到XmlSerializer类的Deserialize方法,将XML进行反序列化。 创建XML序列化公共处理类(XmlSerializeHelper.cs) using System; /// /// /// [XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=false)] // 当该类为Xml根节点时,以此为根节点名称。 [XmlAttribute("AreaName")] // 表现为Xml节点属性。<... areaname="..."> [XmlElementAttribute("AreaId", IsNullable = false)] // 表现为Xml节点。... [XmlArrayAttribute("Areas")] // 表现为Xml层次结构,根为Areas,其所属的每个该集合节点元素名为类名。 [XmlElementAttribute("Area", IsNullable = false)] // 表现为水平结构的Xml节点。... [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; /// C#实体类与XML相互转换 标签:式表 uid 形式 array where ota exception choice 学生 原文地址:https://www.cnblogs.com/amylis_chen/p/11553240.html
using System.IO;
using System.Xml.Serialization;
///
/// XML序列化公共处理类
///
public static class XmlSerializeHelper
{
///
/// 将实体对象转换成XML
///
///
/// 实体对象
public static string XmlSerialize
{
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);
}
}
///
/// 将XML转换成实体对象
///
///
/// XML
public static T DESerializer
{
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);
}
}
}
创建用户信息类,用于示例使用。
/// 用户信息类
///
public class UserInfo
{
///
/// 编号
///
public int ID { get; set; }
///
/// 名称
///
public string Name { get; set; }
///
/// 创建时间
///
public DateTime? CreateTime { get; set; }
}
1.1 示例1:将List与XML相互转换
/// 将List与XML相互转换
///
public static void ListToXmlTest()
{
//获取用户列表
List
//将实体对象转换成XML
string xmlResult = XmlSerializeHelper.XmlSerialize(userList);
//将XML转换成实体对象
List>(xmlResult);
}
///
/// 获取用户信息列表
///
public static List
{
List
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结果:
1.2 示例2:将DataTable与XML相互转换
/// 将DataTable与XML相互转换
///
public static void DataTableToXmlTest()
{
//创建DataTable对象
DataTable dt = CreateDataTable();
//将DataTable转换成XML
string xmlResult = XmlSerializeHelper.XmlSerialize(dt);
//将XML转换成DataTable
DataTable deResult = XmlSerializeHelper.DESerializer
}
///
/// 创建DataTable对象
///
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结果:
2、序列化常用Attribute讲解说明
public class City
public string Name
public string Id
public Area[] Areas
public Area[] Areas
using System.Xml.Serialization;
///
/// 班级信息类
///
[XmlRootAttribute("MyClassInfo", Namespace = "ABC_123", IsNullable = false)]
public class ClassInfo
{
///
/// 班级ID
///
[XmlAttribute("MyClassID")]
public int ClassID { get; set; }
///
/// 班级名称
///
[XmlElementAttribute("MyClassName", IsNullable = false)]
public string ClassName { get; set; }
///
/// 班长人
///
[XmlElementAttribute("MyTeacher", IsNullable = false)]
public string Teacher { get; set; }
///
/// 学生列表
///
[XmlArrayAttribute("MyStudents")]
public List
}
2.2 创建学生信息类(Student.cs)
///
/// 学生信息类
///
[XmlRootAttribute("MyStudent", IsNullable = false)]
public class Student
{
///
/// 学生ID
///
[XmlAttribute("MyStuID")]
public int StuID { get; set; }
///
/// 学生名称
///
[XmlElementAttribute("MyStuName", IsNullable = false)]
public string StuName { get; set; }
///
/// 性别
///
[XmlElementAttribute("MySex", IsNullable = false)]
public string Sex { get; set; }
///
/// 邮箱
///
[XmlIgnoreAttribute]
public string Email { get; set; }
}
2.3 将班级信息转换成XML
/// 将班级信息转换成XML
///
public static void ClassInfoToXml()
{
//获取班级信息
ClassInfo classInfo = GetClassInfo();
//将班级信息转换成XML
string classXml = XmlSerializeHelper.XmlSerialize(classInfo);
}
///
/// 获取班级信息
///
public static ClassInfo GetClassInfo()
{
//创建班级信息
ClassInfo classInfo = new ClassInfo();
classInfo.ClassID = 1;
classInfo.ClassName = "高一(5)班";
classInfo.Teacher = "李老师";
//创建学生列表
List
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结果:
上一篇:C#访问https地址实例