C#实体类(复杂类)与XML互相转换

实体类转换成XML方法:

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

 
复制代码
public static string XmlSerialize<T>(T obj)
{
    using (System.IO.StringWriter sw = new StringWriter())
    {
        Type t = obj.GetType();
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
        serializer.Serialize(sw, obj);
        sw.Close();
        return sw.ToString();
    }
}
复制代码

 

 

例子:

定义实体类

复制代码
    public class root
    {
        public head head { get; set; }
        public body body { get; set; }
    }
    
    public class head
    {
        public string organ { get; set; }
        public string jkxlh { get; set; }
        public string jkid { get; set; }
    }
    
    //注意!body类的vehispara的类型是dynamic 所以需要使用XmlInclude表示body可以解析的类型
    [System.Xml.Serialization.XmlInclude(typeof(JCZ01))]
    [System.Xml.Serialization.XmlInclude(typeof(JCZ02))]
    public partial class body
    {
        public dynamic vehispara { get; set; }//接受动态业务类型 即JCZ01、JCZ02等等
    }
    
    public class JCZ01
    {
        public string tsno { get; set; }
        public string orgcode { get; set; }
        public string teststation { get; set; }
        public string testaddress { get; set; }
        public DateTime? firstauthdate { get; set; }
        public DateTime? jlrzyxrq { get; set; }
        public DateTime? linkdate { get; set; }
        public string legalperson { get; set; }
        public string test { get; set; }
        public string testtel { get; set; }
        public int testlines { get; set; }
        public string status { get; set; }
        public decimal? lng { get; set; }
        public decimal? lat { get; set; }
    }
    
    public class JCZ02 
    {
        public string tsno { get; set; }
        public string testlineno { get; set; }
        public string firstauthdate { get; set; }
        public string testtype { get; set; }
        public string status { get; set; }
        public string gwip { get; set; }
        public string lxpzq { get; set; }
        public string lxpzh { get; set; }
        public string lxpzczj { get; set; }
        public string lxpzdt { get; set; }
        public string jclc { get; set; }
        public string jcbbh { get; set; }
        public string provider { get; set; }
        public string testexpiredade { get; set; }
        public string dynamometer { get; set; }
        public string dprovider { get; set; }
        public string dadate { get; set; }
        public string analyser { get; set; }
        public string aprovider { get; set; }
        public string aadate { get; set; }
        public string flowmeter { get; set; }
        public string fprovider { get; set; }
        public string fadate { get; set; }
        public string smokemeter { get; set; }
        public string sprovider { get; set; }
        public string sadate { get; set; }
        public string tachometer { get; set; }
        public string tprovider { get; set; }
        public string tadate { get; set; }
        public string otsensor { get; set; }
        public string oprovider { get; set; }
        public string oadate { get; set; }
        public string wstype { get; set; }
        public string wsrovider { get; set; }
    }
复制代码

 

 

实体类转XML代码

复制代码
//Linq to sql 获取数据
var query = from sta in det.Org_DetectStation join line in lineCount on sta.StaID equals line.StaID
            where sta.StaID == staid
            select new JCZ01
            {
                tsno = cityid + sta.StaID.Substring(4,2),
                orgcode = cityid + sta.StaID.Substring(4, 2),
                teststation = sta.StaName,
                testaddress = sta.Address,
                firstauthdate = sta.CMADate,
                jlrzyxrq = sta.CMADate,
                linkdate = sta.CMADate,
                legalperson = sta.CEOName,
                test = sta.CEOName,
                testtel = sta.CEOOfficePhone,
                testlines = line.LineCount,
                status = sta.StaState==0?"1":"2",
                lng = sta.Longitude,
                lat = sta.Latitude
            };
List<JCZ01> jcz011 = query.ToList<JCZ01>();
root r = new root();
head h = new head();
h.jkid = Properties.Settings.Default.JKBH;
h.jkxlh = Properties.Settings.Default.JKXLH;
body b = new body();
b.vehispara = jcz011[0];
r.head = h;
r.body = b;
 
string strhxml = XmlSerialize<head>(h);
string strbxml = XmlSerialize<body>(b);
string strrxml = XmlSerialize<root>(r);
复制代码

 

 

生成的XML实例

复制代码
<?xml version="1.0" encoding="utf-16"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <head>
    <jkxlh>BD11F82096F0290DB2866BD266A0CEDF</jkxlh>
    <jkid>23270000</jkid>
  </head>
  <body>
    <vehispara xsi:type="JCZ01">
      <tsno>23270002</tsno>
      <orgcode>23270002</orgcode>
      <teststation>XXXX有限公司</teststation>
      <testaddress>测试</testaddress>
      <firstauthdate>2038-08-11T00:00:00</firstauthdate>
      <jlrzyxrq>2038-08-11T00:00:00</jlrzyxrq>
      <linkdate>2038-08-11T00:00:00</linkdate>
      <legalperson>测试</legalperson>
      <test>测试</test>
      <testtel />
      <testlines>1</testlines>
      <status>1</status>
      <lng xsi:nil="true" />
      <lat xsi:nil="true" />
    </vehispara>
  </body>
</root>
复制代码

 

 

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需注意的问题:

当实体类的string类型字段为null时,序列化成XML时会忽略掉这个字段(即序列化后的XML中没有该节点)

解决的办法我知道的有两个,第一个把该字段赋值为空字符串,另一个就是给类的属性加上XmlElement(IsNullable=true)特性,如:

复制代码
public class JCZ01
    {
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string tsno { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string orgcode { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string teststation { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string testaddress { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public DateTime? firstauthdate { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public DateTime? jlrzyxrq { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public DateTime? linkdate { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string legalperson { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string test { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string testtel { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public int? testlines { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public string status { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public decimal? lng { get; set; }
        [System.Xml.Serialization.XmlElement(IsNullable = true)]
        public decimal? lat { get; set; }
    }
复制代码

 

 

参考:https://www.cnblogs.com/dotnet261010/p/6513618.html

 

出处:https://blog.csdn.net/CGS_______/article/details/84559590

posted on   jack_Meng  阅读(14109)  评论(1编辑  收藏  举报

编辑推荐:
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2016-12-13 巧用Windows 7计划任务设置定时提醒
2016-12-13 vba中MsgBox的参数及用法
2016-12-13 SQL行转列和列转行
2015-12-13 学习汇编语言
2015-12-13 “Hello World”—— 第一个汇编程序
2015-12-13 汇编程序设计上机步骤
2015-12-13 DEBUG命令详细说明

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

支付宝打赏

主题色彩