源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C# XML序列化方法及常用特性总结分析

  • 时间:2020-09-19 00:05 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C# XML序列化方法及常用特性总结分析
本文实例总结了C# XML序列化方法及常用特性。分享给大家供大家参考,具体如下: [b]C#对象XML序列化(一):序列化方法和常用特性[/b] .Net Framework提供了对应的System.Xml.Seriazliation.XmlSerializer负责把对象序列化到XML,和从XML中反序列化为对象。Serializer的使用比较直观,需要多注意的是XML序列化相关的Attribute,怎么把这些attribute应用到我们的对象,以及对象公共属性上面去,生成满足预期格式的XML。 这里列出了最常用的方法和特性,涵盖日常大部分的转换工作,希望大家在工作中快速上手。为了给大家直观的印象,这里给出具体的使用代码,为了节省篇幅,代码异常处理没有添加,各位同学使用的时候酌情添加。 [b]1. Serializer方法[/b] 下面的方法封装了XmlSerializer的调用,这里列出了参数最全的一个版本,具体使用的时候需适当添加重载:
public static class XmlSerializer
{
  public static void SaveToXml(string filePath, object sourceObj, Type type, string xmlRootName)
  {
    if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
    {
      type = type != null ? type : sourceObj.GetType();
      using (StreamWriter writer = new StreamWriter(filePath))
      {
        System.Xml.Serialization.XmlSerializer xmlSerializer = string.IsNullOrWhiteSpace(xmlRootName) ?
          new System.Xml.Serialization.XmlSerializer(type) :
          new System.Xml.Serialization.XmlSerializer(type, new XmlRootAttribute(xmlRootName));
        xmlSerializer.Serialize(writer, sourceObj);
      }
    }
  }
  public static object LoadFromXml(string filePath, Type type)
  {
    object result = null;
    if (File.Exists(filePath))
    {
      using (StreamReader reader = new StreamReader(filePath))
      {
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
        result = xmlSerializer.Deserialize(reader);
      }
    }
    return result;
  }
}

[b]2. 序列化常用Attribute讲解说明:[/b]
[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]  // 忽略该元素的序列化。

[b]3. 详细举例说明[/b] 这里用简单的城市,区域和街区作为例子,具体示范一下上面的规则。
[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;
  }
}

根据以上类型,我们mock一些数据,然后用步骤1给出的Util方法输出:
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>

下面我们开始具体分析结果,其中包含一些很有用的[b]结论和注意事项[/b]: 1. xml的版本,编码,以及命名空间xmlns:xsi,xmlns:xsd为Framework自动添加。 2. 因为我们用City对象作为根节点,所以根节点名称为我们定义的"MyCity"。 但是,注意!这里指的是用City自身直接做根节点,如果是City集合比如City[],此时,该名称失效,系统会自动生成名称ArrayOfCity作为根节点名称(ArrayOf+类名),或者我们手动指定名称,这个就是在给大家的SaveToXml()方法中,参数xmlRootName的作用。 3. 如果以City为根节点并在XmlRootAttribute特性中给定名称,同时也手动指定了xmlRootName,系统会以手动指定的名称为准。 4. AreaName,AreaId,同为Area类的公共属性,一个被解释成属性,一个被解释成子节点。 Areas集合被解释成了层次结构,Streets集合被解释成了水平结构。 这两组区别最能体现不同序列化Attribute的用法。 [b]PS:小编这里再来为大家推荐几款关于xml操作的在线工具供大家免费使用。相信在以后开发中可以用的到:[/b] [b]在线XML格式化/压缩工具: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]xml代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] [b]HTML/XML转义字符对照表: [/b][url=http://tools.jb51.net/table/html_escape]http://tools.jb51.net/table/html_escape[/url] 更多关于C#相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/266.htm]C#中XML文件操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/165.htm]C#常见控件用法教程[/url]》、《[url=http://www.1sucai.cn/Special/125.htm]WinForm控件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/116.htm]C#数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/478.htm]C#面向对象程序设计入门教程[/url]》及《[url=http://www.1sucai.cn/Special/227.htm]C#程序设计之线程使用技巧总结[/url]》 希望本文所述对大家C#程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部