你的位置:首页 > ASP.net教程

[ASP.net教程][.net 面向对象程序设计进阶] 序列化(Serialization)(三) 通过接口IXmlSerializable实现XML序列化及XML通用类


[.net 面向对象程序设计进阶] (11) 序列化(Serialization)(三) 通过接口I

本节导读:本节主要介绍通过序列化接口I 

读前必备:

A.类和类的实例  [.net 面向对象编程基础]  (9) 类和类的实例

B.类的成员        [.net 面向对象编程基础]  (10) 类的成员(字段、属性、方法)

C.数组与集合    [.net 面向对象编程基础]  (17) 数组与集合

D.泛型             [.net 面向对象编程基础]  (18) 泛型

E.LINQ使用     [.net 面向对象编程基础] (20) LINQ使用

1. 通过序列化接口I

   命名空间:System.

   接口:I

   方法:

   

   void Read

   void Write

下面通过示例介绍关于序列化接口的使用,还是通过博客园文章为例:

定义文章实体类及文章调用方法: 

public class MyBlogs{  /// <summary>  /// 获取我的博客园中文章  /// </summary>  /// <returns></returns>  public static List<MyArticle> GetMyArticle(int count)  {    var document = XDocument.Load(      "http://wcf.open.cnblogs.com/blog/u/yubinfeng/posts/1/" + count      );    List<MyArticle> myArticleList = new List<MyArticle>();    var elements = document.Root.Elements();    //在进行这个工作之前,我们先获取我博客中的文章列表    var result = elements.Where(m => m.Name.LocalName == "entry").Select(myArticle => new MyArticle    {      id = Convert.ToInt32(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "id").Value),      title = myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "title").Value,      published = Convert.ToDateTime(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "published").Value),      updated = Convert.ToDateTime(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "updated").Value),      diggs = Convert.ToInt32(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "diggs").Value),      views = Convert.ToInt32(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "views").Value),      comments = Convert.ToInt32(myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "comments").Value),      summary = myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "summary").Value,      link = myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "link").Attribute("href").Value,      author = myArticle.Elements().SingleOrDefault(x => x.Name.LocalName == "author").Elements().SingleOrDefault(x => x.Name.LocalName == "name").Value    }).OrderByDescending(m => m.published);    myArticleList.AddRange(result);    return myArticleList;  }}/// <summary/// 我的博客文章实体类/// </summary>public class MyArticle{  /// <summary>  /// 文章编号  /// </summary>  public int id { get; set; }  /// <summary>  /// 文章标题  /// </summary>  public string title { get; set; }  /// <summary>  /// 文章摘要  /// </summary>  public string summary { get; set; }  /// <summary>  /// 发布时间  /// </summary>  public DateTime published { get; set; }  /// <summary>  /// 最后更新时间  /// </summary>  public DateTime updated { get; set; }  /// <summary>  /// URL地址  /// </summary>  public string link { get; set; }  /// <summary>  /// 推荐数  /// </summary>  public int diggs { get; set; }  /// <summary>  /// 浏览量  /// </summary>  public int views { get; set; }  /// <summary>  /// 评论数  /// </summary>  public int comments { get; set; }  /// <summary>  /// 作者  /// </summary>  public string author { get; set; }}

/// <summary>/// 序列化/// 下面注释项,可根据需要使用/// </summary>/// <param name="Obj"></param>/// <returns></returns>public static string ObjectTostring "";  = new //settings.Omit//去除  settings.Encoding = Encoding.Default;//使用默认编码  //settings.IndentChars = "--"; //使用指定字符缩进  settings.Indent = true; //换行缩进  using (System.IO.MemoryStream mem = new MemoryStream())  {    using ( //去除默认命名空间      new "", "");      = new = Encoding.Default.GetString(mem.ToArray());  }  return /// <summary>/// 反序列化 /// </summary>/// <typeparam name="T"></typeparam>/// <param name="str"></param>/// <returns></returns>public static T ObjectTostring str) where T : class{  object obj;  using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str)))  {    using ( = new typeof(T));      obj = formatter.Deserialize(reader);    }  }  return obj as T;}

调用如下:

//命名空间:System.//接口:I//方法://(1)获取我博客园中最后10篇文章 (实际上这个过程也是反序列化)List<MyArticle> myArticleList = MyBlogs.GetMyArticle(10);//序列化并输出string  ObjectTo//序列化List<MyArticle> myNewArticleList = ObjectTo(//遍历输出反序化的新对象myNewArticleListmyNewArticleList.ForEach(m =>  Console.WriteLine("文章编号:" + m.id + "\n文章标题:" + m.title));

运行结果如下:

 

 2.

我们在序列化

名称

描述

表示一个特性对象的集合,这些对象控制如何序列化和反序列化对象

指定应将特定的类成员序列化为元素数组

指定可以放置在序列化数组中的派生类型

表示对象的集合

指定应将类成员作为特性序列化

指定可以通过使用枚举来进一步消除成员的歧义

在序列化或反序列化包含对象时,指示公共字段或属性表示元素

表示的集合,将其用于它重写序列化类的默认方式

控制如何序列化枚举成员

指示方法不序列化公共字段或公共读/写属性值

允许在它序列化或反序列化对象时识别类型

控制视为根元素的属性目标的序列化

当序列化或反序列化时,想指示应将此成员作为文本处理

控制当属性目标由序列化时生成的结构

指定成员(返回对象的数组的字段)可以包含属性

指定成员可以包含对象,该对象表示在序列化或反序列化的对象中没有相应成员的所有元素

表示对象的集合

为UnKnowAttribute提供数据

允许你在使用序列化或反序列化时重写属性、字段和类特性

为UnknownElement事件提供数据

指定目标属性、参数、返回值或类成员包含与文档中所用命名空间关联的前缀

为UnknownNode时间提供数据

将对象序列化到文档中和从文档中反序列化对象,使你得以控制如何将对象编码到中

包含用于在文档实例中生成限定名的命名空间和前缀

包含从一种类型到另一种类型的映射

  更多更详细的说明,请看官方API:http://msdn.microsoft.com/zh-cn/library/System.

3.

最后整理一个

文件名:

代码如下:

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.IO; 7 using System.Data; 8 using System. 9 using System. 10 using System. 11  12 namespace Common 13 { 14   /// <summary> 15   ///  16   /// Author:YuBinfeng 17   /// Data:2015/07/10 18   /// </summary> 19   public class  20   { 21    22     #region  23  24     #region 将 25     /// <summary> 26     /// 将 27     /// </summary> 28     /// <param name=" 29     /// <param name="filePath"></param> 30     /// <returns></returns> 31     public static bool Writestring string filePath) 32     { 33       try 34       {         35           File.WriteAllText(filePath,  36           return true;        37       } 38       catch 39       { 40         return false; 41       } 42     } 43     #endregion 44  45     #region 从指定的路径读取 46     /// <summary> 47     /// 将 48     /// </summary> 49     /// <param name=" 50     /// <param name="filePath"></param> 51     /// <returns></returns> 52     public static string Readstring filePath) 53     { 54       try 55       { 56         new  57          58         return  59       } 60       catch (Exception ex) 61       { 62         return ""; 63       } 64     } 65     #endregion 66  67     #region 读取 68     /// <summary> 69     /// 读取 70     /// </summary> 71     /// <param name="source"></param> 72     /// <param name="</param> 73     /// <param name="nodeName">节点名称</param> 74     /// <returns>节点内容</returns> 75     public static object GetNodeValue(string source, string nodeName) 76     { 77       new  78       if (  79       { 80         xd.Load(source); 81       } 82       else 83       { 84         xd.Load 85       } 86        xd.DocumentElement; 87       "//" + nodeName); 88       if (xn != null) 89       { 90         return xn.InnerText; 91       } 92       else 93       { 94         return null; 95       } 96     } 97  98     /// <summary> 99     /// 读取100     /// </summary>101     /// <param name="source"></param>102     /// <param name="nodeName">节点名称</param>103     /// <returns>节点内容</returns>104     public static object GetNodeValue(string source, string nodeName)105     {106       if (source == null || nodeName == null || source == "" || nodeName == "" || source.Length < nodeName.Length * 2)107       {108         return null;109       }110       else111       {112         int start = source.IndexOf("<" + nodeName + ">") + nodeName.Length + 2;113         int end = source.IndexOf("</" + nodeName + ">");114         if (start == -1 || end == -1)115         {116           return null;117         }118         else if (start >= end)119         {120           return null;121         }122         else123         {124           return source.Substring(start, end - start);125         }126       }127     }128     #endregion129 130     #region 更新131     /// <summary>132     /// 更新133     /// </summary>134     /// <param name="filePath">文件路径</param>135     /// <param name="nodeName">节点名称</param>136     /// <param name="nodeValue">更新内容</param>137     /// <returns>更新是否成功</returns>138     public static bool UpdateNode(string filePath, string nodeName, string nodeValue)139     {140       bool flag = false;141 142       new 143       xd.Load(filePath);144        xd.DocumentElement;145       "//" + nodeName);146       if (xn != null)147       {148         xn.InnerText = nodeValue;149         flag = true;150       }151       else152       {153         flag = false;154       }155       return flag;156     }157     #endregion158 159     #region 操作160     /// <summary>161     /// 获得162     /// </summary>163     /// <param name="TableName"></param>164     /// <returns></returns>165     public static string GetNodeInfoByNodeName(string path, string nodeName)166     {167       string "";168       new 169       170       System. 171       System."//" + nodeName);172       if (node != null)173       {174          node.InnerText;175       }176       return 177     }178     #endregion179     #endregion180 181     #region 共有属性182     /// <summary>183     /// 184     /// </summary>185     public enum 186     {187       File,188       String189     };190     #endregion191 192     #region 193 194     #region 读取195     /// <summary>196     /// 读取197     /// </summary>198     /// <param name="source"></param>199     /// <param name="</param>200     /// <returns>DataSet</returns>201     public static DataSet GetDataSet(string source, 202     {203       DataSet ds = new DataSet();204       if ( 205       {206         ds.Read207       }208       else209       {210         new 211         xd.Load212         new 213         ds.Read214       }215       return ds;216     }217 218     #endregion219 220     #region 获取一个字符串221     /// <summary>222     /// 获取一个字符串223     /// </summary>224     /// <param name="含有</param>225     public static void get_string ref DataSet ds)226     {227       System.new 228       xd.Load229       new 230       ds.Read231       xnr.Close();232       int a = ds.Tables.Count;233     }234     #endregion235 236     #region 读取237     /// <summary>238     /// 读取239     /// </summary>240     /// <param name="source"></param>241     /// <param name="</param>242     /// <param name="tableName">表名称</param>243     /// <returns>DataTable</returns>244     public static DataTable GetTable(string source, string tableName)245     {246       DataSet ds = new DataSet();247       if ( 248       {249         ds.Read250       }251       else252       {253         new 254         xd.Load255         new 256         ds.Read257       }258       return ds.Tables[tableName];259     }260     #endregion261 262     #region 读取263     /// <summary>264     /// 读取265     /// </summary>266     /// <param name="source"></param>267     /// <param name="</param>268     /// <param name="tableName">表名</param>269     /// <param name="rowIndex">行号</param>270     /// <param name="colName">列名</param>271     /// <returns>值,不存在时返回Null</returns>272     public static object GetTableCell(string source, string tableName, int rowIndex, string colName)273     {274       DataSet ds = new DataSet();275       if ( 276       {277         ds.Read278       }279       else280       {281         new 282         xd.Load283         new 284         ds.Read285       }286       return ds.Tables[tableName].Rows[rowIndex][colName];287     }288     #endregion289 290     #region 读取291     /// <summary>292     /// 读取293     /// </summary>294     /// <param name="source"></param>295     /// <param name="</param>296     /// <param name="tableName">表名</param>297     /// <param name="rowIndex">行号</param>298     /// <param name="colIndex">列号</param>299     /// <returns>值,不存在时返回Null</returns>300     public static object GetTableCell(string source, string tableName, int rowIndex, int colIndex)301     {302       DataSet ds = new DataSet();303       if ( 304       {305         ds.Read306       }307       else308       {309         new 310         xd.Load311         new 312         ds.Read313       }314       return ds.Tables[tableName].Rows[rowIndex][colIndex];315     }316     #endregion317 318     #region 将DataTable写入319     /// <summary>320     /// 将DataTable写入321     /// </summary>322     /// <param name="dt">含有数据的DataTable</param>323     /// <param name="filePath">文件路径</param>324     public static void SaveTableToFile(DataTable dt, string filePath)325     {326       DataSet ds = new DataSet("Config");327       ds.Tables.Add(dt.Copy());328       ds.Write329     }330     #endregion331 332     #region 将DataTable以指定的根结点名称写入文件333     /// <summary>334     /// 将DataTable以指定的根结点名称写入文件335     /// </summary>336     /// <param name="dt">含有数据的DataTable</param>337     /// <param name="rootName">根结点名称</param>338     /// <param name="filePath">文件路径</param>339     public static void SaveTableToFile(DataTable dt, string rootName, string filePath)340     {341       DataSet ds = new DataSet(rootName);342       ds.Tables.Add(dt.Copy());343       ds.Write344     }345     #endregion346 347     #region 使用DataSet方式更新348     /// <summary>349     /// 使用DataSet方式更新350     /// </summary>351     /// <param name="filePath"></param>352     /// <param name="tableName">表名称</param>353     /// <param name="rowIndex">行号</param>354     /// <param name="colName">列名</param>355     /// <param name="content">更新值</param>356     /// <returns>更新是否成功</returns>357     public static bool UpdateTableCell(string filePath, string tableName, int rowIndex, string colName, string content)358     {359       bool flag = false;360       DataSet ds = new DataSet();361       ds.Read362       DataTable dt = ds.Tables[tableName];363 364       if (dt.Rows[rowIndex][colName] != null)365       {366         dt.Rows[rowIndex][colName] = content;367         ds.Write368         flag = true;369       }370       else371       {372         flag = false;373       }374       return flag;375     }376     #endregion377 378     #region 使用DataSet方式更新379     /// <summary>380     /// 使用DataSet方式更新381     /// </summary>382     /// <param name="filePath"></param>383     /// <param name="tableName">表名称</param>384     /// <param name="rowIndex">行号</param>385     /// <param name="colIndex">列号</param>386     /// <param name="content">更新值</param>387     /// <returns>更新是否成功</returns>388     public static bool UpdateTableCell(string filePath, string tableName, int rowIndex, int colIndex, string content)389     {390       bool flag = false;391 392       DataSet ds = new DataSet();393       ds.Read394       DataTable dt = ds.Tables[tableName];395 396       if (dt.Rows[rowIndex][colIndex] != null)397       {398         dt.Rows[rowIndex][colIndex] = content;399         ds.Write400         flag = true;401       }402       else403       {404         flag = false;405       }406       return flag;407     }408     #endregion409 410     #endregion411 412     #region 413 414     /// <summary>415     /// 序列化416     /// 下面注释项,可根据需要使用417     /// </summary>418     /// <param name="Obj"></param>419     /// <returns></returns>420     public static string ObjectTo421     {422       string "";423       new 424       //settings.Omit//去除425       settings.Encoding = Encoding.Default;//使用默认编码426                         //settings.IndentChars = "--"; //使用指定字符缩进427       settings.Indent = true; //换行缩进428 429       using (System.IO.MemoryStream mem = new MemoryStream())430       {431         using ( 432         {433           //去除默认命名空间434           new 435           ns.Add("", "");436 437           new 438           formatter.Serialize(writer, Obj, ns);439         }440          Encoding.Default.GetString(mem.ToArray());441       }442       return 443     }444 445     /// <summary>446     /// 反序列化 447     /// </summary>448     /// <typeparam name="T"></typeparam>449     /// <param name="str"></param>450     /// <returns></returns>451     public static T ObjectTostring str) where T : class452     {453       object obj;454       using (System.IO.MemoryStream mem = new MemoryStream(Encoding.Default.GetBytes(str)))455       {456         using ( 457         {458           new typeof(T));459           obj = formatter.Deserialize(reader);460         }461       }462       return obj as T;463     }464 465     #endregion466 467   }468 }

View Code

4. 本节要点:

A.本节主要介绍了通过序列化接口I

B.

C.最后提供了一个序列化及

==============================================================================================  

 返回目录

 <如果对你有帮助,记得点一下推荐哦,如有有不明白或错误之处,请多交流>  

<对本系列文章阅读有困难的朋友,请先看《.net 面向对象编程基础》>

<转载声明:技术需要共享精神,欢迎转载本博客中的文章,但请注明版权及URL>

.NET 技术交流群:467189533    .NET 程序设计

==============================================================================================