上篇已经介绍到了通过序列化器将内容写入到xml文件中。这里还是用person类来写。
<span style="font-family:Microsoft YaHei;font-size:18px;">person p=new person() {Name = "istari", Age = 22, Email = "1061399756@qq.com"};</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">MySerialize(p, typeof(person));</span>
<span style="font-family:Microsoft YaHei;font-size:18px;">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"); }</span>
其中用到反射来获取person类中的所有属性。
<span style="font-family:Microsoft YaHei;font-size:18px;"><?xml version="1.0" encoding="utf-8"?> <person> <Name>istari</Name> <Age>22</Age> <Email>1061399756@qq.com</Email> </person></span>
以上就是XML(6)自己写一个xml序列化器的内容,更多相关内容请关注PHP中文网(www.php.cn)!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号