标签导航:

上篇已经介绍到了通过序列化器将内容写入到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(&#39;.&#39;) + 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>