1、首先写一个person对象
person p=new person() {Name = "istari", Age = 22, Email = "1061399756@qq.com"};2、然后写一个方法用于把这个对象用我们的方式进行序列化,其中这里用到了反射。
MySerialize(p, typeof(person));
3、在这个方法里面写自己的序列化器
private static void MySerialize(object obj, Type type) { //创建一个Xdocument对象 Xdocument document = new Xdocument(); //写入xml文件,把类名作为根节点 string nsStr = type.ToString(); string className = nsStr.Substring(nsStr.LastIndexOf('.') + 1); //写入根节点 XElement rootElement = new XElement(className); //获取当前类型中的所有的属性 PropertyInfo[] properties = type.GetProperties(); //遍历 foreach (PropertyInfo item in properties) { rootElement .SetElementValue (item.Name ,item.GetValue (obj,null)); } document .Add (rootElement ); document .Save (className +".xml"); }其中用到反射来获取person类中的所有属性。
Result
istari 22 1061399756@qq.com
以上就是XML(6)自己写一个xml序列化器的内容,更多相关内容请关注PHP中文网(www.kaotop.com)!



