文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

一、实体类转换成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、定义实体类

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public class Request
    {

        public string System { get; set; }
        public string SecurityCode { get; set; }
        public PatientBasicInfo PatientInfo { get; set; }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class PatientBasicInfo
    {
        public string PatientNo { get; set; }
        public string PatientName { get; set; }
        public string Phoneticize { get; set; }
        public string Sex { get; set; }
        public string Birth { get; set; }
        public string BirthPlace { get; set; }
        public string Country { get; set; }
        public string Nation { get; set; }
        public string IDNumber { get; set; }
        public string SecurityNo { get; set; }
        public string Workunits { get; set; }
        public string Address { get; set; }
        public string ZIPCode { get; set; }
        public string Phone { get; set; }
        public string ContactPerson { get; set; }
        public string ContactShip { get; set; }
        public string ContactPersonAdd { get; set; }
        public string ContactPersonPhone { get; set; }
        public string OperationCode { get; set; }
        public string OperationName { get; set; }
        public string OperationTime { get; set; }
        public string CardNo { get; set; }
        public string ChangeType { get; set; }

    }

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

Request patientIn = new Request();
            patientIn.System = "HIS";
            patientIn.SecurityCode = "HIS5";

            PatientBasicInfo basicInfo = new PatientBasicInfo();
            basicInfo.PatientNo = "1234";
            basicInfo.PatientName = "测试";
            basicInfo.Phoneticize = "";
            basicInfo.Sex = "1";
            basicInfo.Birth = "";
            basicInfo.BirthPlace = "";
            basicInfo.Country = "";
            basicInfo.Nation = "";
            basicInfo.IDNumber = "";
            basicInfo.SecurityNo = "";
            basicInfo.Workunits = "";
            basicInfo.Address = "";
            basicInfo.ZIPCode = "";
            basicInfo.Phone = "";
            basicInfo.ContactShip = "";
            basicInfo.ContactPersonPhone = "";
            basicInfo.ContactPersonAdd = "";
            basicInfo.ContactPerson = "";
            basicInfo.ChangeType = "";
            basicInfo.CardNo = "";
            basicInfo.OperationCode = "";
            basicInfo.OperationName = "";
            basicInfo.OperationTime = "";

            patientIn.PatientInfo = basicInfo;

            //序列化
            string strxml = XmlSerializeHelper.XmlSerialize<Request>(patientIn);

3、生成的XML实例

<?xml version="1.0" encoding="utf-16"?>
<Request xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <System>HIS</System>
  <SecurityCode>HIS5</SecurityCode>
  <PatientInfo>
    <PatientNo>1234</PatientNo>
    <PatientName>测试</PatientName>
    <Phoneticize />
    <Sex>1</Sex>
    <Birth />
    <BirthPlace />
    <Country />
    <Nation />
    <IDNumber />
    <SecurityNo />
    <Workunits />
    <Address />
    <ZIPCode />
    <Phone />
    <ContactPerson />
    <ContactShip />
    <ContactPersonAdd />
    <ContactPersonPhone />
    <OperationCode />
    <OperationName />
    <OperationTime />
    <CardNo />
    <ChangeType />
  </PatientInfo>
</Request>

二、将XML转换成实体类

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

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)
     {
            return null;
     }
}

示例:

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

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

 三、将DataTable转换成XML

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

四、将XML转换成DataTable

//反序列化,将XML转换成字符串
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进行反序列化。

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

到此这篇关于C#实现实体类和XML相互转换的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯