C#实体类与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 = "[email protected]" });
studentList.Add(new Student() { StuID = 2, StuName = "李四", Sex = "女", Email = "[email protected]" });
studentList.Add(new Student() { StuID = 3, StuName = "王五", Sex = "男", Email = "[email protected]" });
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>

原文地址:https://www.cnblogs.com/amylis_chen/p/11553240.html

时间: 2024-11-03 23:25:36

C#实体类与XML相互转换的相关文章

简单实体类和xml文件的相互转换

最近写一个题目,要求将一组员工实体类转换成xml文件,或将xml文件转换成一组实体类.题目不难,但写完感觉可以利用泛型和反射将任意一个实体类和xml文件进行转换.于是今天下午立马动手 试了下,做了个简单的模型,可以将简单的实体类和xml文件进行相互转换,但对实体类的属性类型有限制,目前只支持String, Integer, Double三种类型.但是后面可以扩展. 我的大概思路是这样的,只要能拿到实体类的类型信息,我就能拿到实体类的全部字段名称和类型,拼属性的set和get方法更是简单明了,这时

利用JAXB实现java实体类和xml互相转换

1.应用场景 在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换 2.Demo 2.1 student.java 实体类,包含list(set同理).map.Teacher.Date 类型的属性 package jaxb; import java.util.Date; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccess

C#实体类生成XML与XML Schema文档

一.实体类生成XML 1 private void CreateXML() 2 { 3 Type[] objType = DBEntityRegst(); 4 foreach (var item in objType) 5 { 6 if (item == null) 7 { 8 break; 9 } 10 11 XmlDocument doc = new XmlDocument(); 12 13 //<?xml version="1.0"?> 14 XmlDeclarati

利用XStream实现实体类与xml的转换

package com.wanhua.util; import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.xml.DomDriver; /** * 利用XStream实现实体类与xml的转换 *  * @author w_xfpenga *  *         2014-11-27 */public class XStream2Text { static XStream xStream = new X

NHibernate生成实体类、xml映射文件

最近工作电脑装完win10后,之前使用的codeSmith安装不了,索性自己写一个. 界面比较简单,如下图: 第一行为Oracle数据库的连接字符串.连接成功后,填充表到第4行的下拉列表中. 第二行为实体类命名空间. 第三行为保存生成类.xml文件选择文件夹. 1 private void btnConnect_Click(object sender, RoutedEventArgs e) 2 { 3 try 4 { 5 using (OracleConnection conn = new Or

Spring 简单的配置和操作 ( 创建实体类, 配置XML文件, 调试 )

< 1 > 实体类 Person package java_spring.modle; /** * 一个实体类( Person ) */ public class Person { private int userId; private String userName; private String userAge; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId

C#序列化s实体类成Xml,去除空格、换行符以及命名空间

序列化实体类成为一个干净的Xml,不带空格.换行符以及命名空间 /// <summary> /// 序列化成XML /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string X

读取xml节点值生成一个实体类,读取xml所有节点值,读取所有xml所有节点名称

public partial class WebFormClassByEntity : System.Web.UI.Page    {        List<string> list = new List<string>();//存放所有节点名称        protected void Page_Load(object sender, EventArgs e)        {            //读取xml的文件路径            string filePah

[Unity]C#中 将XML和实体类之间进行相互转换的工具类

using System; using System.Xml; using System.Xml.Serialization; using System.IO; namespace LOTool { public class LO_XMLTool { #region 反序列化 /// <summary> /// 反序列化 /// </summary> /// <param name="type">类型</param> /// <pa