這兩天,應要求做一個C/S的小程序,考慮到程序簡潔小巧,存數據的方式不使用數據庫,而是直接存入XML文檔中保存。為了把復雜實體類裡面的屬性存入XML,我們可以使用C#有的反射機制,做一個簡單的通用工具類來實現。(需要設置屬性為public)
弱弱的問一句,這種“序列化”的說法是對的嗎?如果我說錯了記得提醒我一下(⊙v⊙)
實現類代碼:
using System; using System.Reflection; using System.Xml.Linq; namespace MyTool { public static class ObjectToXml { public static string Path { get { return String.Format(@"{0}/{1}.xml", 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 xmltest { 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" } } }; ObjectToXml.Intit(a); Console.ReadKey(); } } public 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; } } }
最後的效果: