
person p=new person() {Name = "istari", Age = 22, Email = "1061399756@qq.com"};MySerialize(p, typeof(person));
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类中的所有属性。
istari 22 1061399756@qq.com
以上就是XML(6)自己写一个xml序列化器的内容,更多相关内容请关注PHP中文网(www.iotsi.net)!