XML(6)自己写一个xml序列化器

前端之家收集整理的这篇文章主要介绍了XML(6)自己写一个xml序列化器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

上篇已经介绍到了通过序列化器将内容写入到xml文件中。这里还是用person类来写。

1、首先写一个person对象

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">person p=new person() {Name = "istari",Age = 22,Email = "1061399756@qq.com"};</span>

2、然后写一个方法用于把这个对象用我们的方式进行序列化,其中这里用到了反射。

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">MySerialize(p,typeof(person));</span>

3、在这个方法里面写自己的序列化器

  1. <span style="font-family:Microsoft YaHei;font-size:18px;">private static void MySerialize(object obj,Type type)
  2. {
  3. //创建一个XDocument对象
  4. XDocument document = new XDocument();
  5. //写入xml文件,把类名作为根节点
  6. string nsStr = type.ToString();
  7. string className = nsStr.Substring(nsStr.LastIndexOf('.') + 1);
  8. //写入根节点
  9. XElement rootElement = new XElement(className);
  10. //获取当前类型中的所有的属性
  11. PropertyInfo[] properties = type.GetProperties();
  12. //遍历
  13. foreach (PropertyInfo item in properties)
  14. {
  15. rootElement .SetElementValue (item.Name,item.GetValue (obj,null));
  16. }
  17. document .Add (rootElement );
  18. document .Save (className +".xml");
  19. }</span>

其中用到反射来获取person类中的所有属性


Result

  1. <span style="font-family:Microsoft YaHei;font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
  2. <person>
  3. <Name>istari</Name>
  4. <Age>22</Age>
  5. <Email>1061399756@qq.com</Email>
  6. </person></span>

猜你在找的XML相关文章