C#model类与XML转换类

Json作为现在API中通用的数据传输格式,目前有Newtonsoft.Json.dll进行转换,那么XML是不是有相关的方法可以转换呢?

原来也是有的,不过需要一定的编写。

转自https://www.cnblogs.com/dotnet261010/p/6513618.html

1、代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml.Serialization;

namespace OAServiceInvoke
{
    public class XMLSerialize
    {
        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();
            }
        }

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

2、序列化常用Attribute讲解说明:转自http://blog.csdn.net/zzy7075/article/details/50770062


[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的具体格式了。


比如如下的Model类

    [XmlRootAttribute("MyCity", Namespace = "abc.abc", IsNullable = false)]
    public class City
    {
        [XmlAttribute("CityName")] 
        public string Name
        {
            get;
            set;
        }

        [XmlAttribute("CityId")] 
        public string Id
        {
            get;
            set;
        }

        [XmlArrayAttribute("Areas")]
        public Area[] Areas
        {
            get;
            set;
        }
    }

    [XmlRootAttribute("MyArea")]
    public class Area
    {
        [XmlAttribute("AreaName")] 
        public string Name
        {
            get;
            set;
        }

        [XmlElementAttribute("AreaId", IsNullable = false)]
        public string Id
        {
            get;
            set;
        }

        [XmlElementAttribute("Street", IsNullable = false)]
        public string[] Streets
        {
            get;
            set;
        }
    }

经过如下的代码转换:

    static void Main(string[] args)
    {
        Area area1 = new Area();
        area1.Name = "Pudong";
        area1.Id = "PD001";
        area1.Streets = new string [] { "street 001", "street 002" };
        Area area2 = new Area();
        area2.Name = "Xuhui";
        area2.Id = "XH002";
        area2.Streets = new string [] { "street 003", "street 004" };

        City city1 = new City();
        city1.Name = "Shanghai";
        city1.Id = "SH001";
        city1.Areas = new Area[] { area1, area2 };

        XmlSerializer.SaveToXml(@"C:\temp\XML\output003.xml", city1);
    }

就变成这样的XML

<?xml version="1.0" encoding="utf-8"?>
<MyCity xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        CityName="Shanghai" CityId="SH001" xmlns="abc.abc">
  <Areas>
    <Area AreaName="Pudong">
      <AreaId>PD001</AreaId>
      <Street>street 001</Street>
      <Street>street 002</Street>
    </Area>
    <Area AreaName="Xuhui">
      <AreaId>XH002</AreaId>
      <Street>street 003</Street>
      <Street>street 004</Street>
    </Area>
  </Areas>
</MyCity>


3、如果要去掉根节点的xmlns:xsd和xmlns:xsi属性

则需要将序列化的方法修改为:


        public static string XmlSerialize<T>(T obj)
        {
            using (StringWriter sw = new StringWriter())
            {
                Type t = obj.GetType();
                // 强制指定命名空间,覆盖默认的命名空间  
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add(string.Empty, string.Empty);  
                
                XmlSerializer serializer = new XmlSerializer(obj.GetType());

                // 序列化时增加namespaces
                serializer.Serialize(sw, obj, namespaces);

                sw.Close();
                return sw.ToString();
            }
        }



知行办公,专业移动办公平台
 https://zx.naton.cn/
【总监】十二春秋之,3483099@qq.com;
【Master】zelo,616701261@qq.com;
【运营】运维艄公,897221533@qq.com;
【产品设计】流浪猫,364994559@qq.com;
【体验设计】兜兜,2435632247@qq.com;
【iOS】淘码小工,492395860@qq.com;iMcG33K,imcg33k@gmail.com;
【Android】人猿居士,1059604515@qq.com;思路的顿悟,1217022114@qq.com;
【java】首席工程师MR_W,feixue300@qq.com;
【测试】土镜问道,847071279@qq.com;
【数据】fox009521,42151960@qq.com;
【安全】保密,你懂的。





  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值