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

[ASP.net教程]C#实体类序列化为XML


  这两天,应要求做一个C/S的小程序,考虑到程序简洁小巧,存数据的方式不使用数据库,而是直接存入

弱弱的问一句,这种“序列化”的说法是对的吗?如果我说错了记得提醒我一下(⊙v⊙)

实现类代码:

using System;using System.Reflection;using System.namespace MyTool{  public static class ObjectTopublic static string Path    {      get { return String.Format(@"{0}/{1}.", Environment.CurrentDirectory,DateTime.Now.Day.ToString()); }    }    public static void Intit(object ob)    {      XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),        new XElement("Data")); //建立跟节点 <Data></Data>      Process(ob,doc.Element("Data"));      doc.Save(Path);    }    private static void Process(object ob,XElement doc)    {      XElement data = doc;      string ClassName = ob.GetType().Name;      data.Add(new XElement(ClassName));//取类名 添加一个节点      PropertyInfo[] properties = ob.GetType().GetProperties(BindingFlags.Instance |BindingFlags.Public);      foreach (var item in properties)      {        string type = item.GetValue(ob).GetType().Name;        if (type.ToLower() == "string" || type.ToLower() == "int32" || type.ToLower() == "double")//判断属性是否是基本类型比如strin int double 若是,则建立节点并赋值        {          XElement ChildNode = data.Element(ClassName);          ChildNode.Add(new XElement(item.Name, item.GetValue(ob)));        }        else //否则,递归运行Process函数        {          Process(item.GetValue(ob), data.Element(ClassName));        }      }    }  }}

View Code

使用:

using System;using MyTool;namespace class Program  {    static void Main(string[] args)    {      var a = new student      {        Name = "memeda", age = 10,gg=1.5,        more=new info        {          boy="nan",          moreinfo=new moreinfo          {            mv="mv"          }        }      };      ObjectTopublic class student  {    public string Name { get; set; }    public int age { get; set; }    public double gg { get; set; }    public info more { get; set; }  }  public class info  {    public moreinfo moreinfo { get; set; }    public string boy { get; set; }  }  public class moreinfo  {    public string mv { get; set; }  }}

最后的效果: