Home  >  Article  >  Backend Development  >  XML (6) Write an xml serializer yourself

XML (6) Write an xml serializer yourself

黄舟
黄舟Original
2017-02-10 16:35:071517browse

The previous article has introduced writing content into xml files through serializers. Here we still use the person class to write.

1. First write a person object

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

2. Then write a method to serialize this object in our way , where reflection is used.

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

3. Write your own serializer in this method


<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>

Used in Reflection to get all properties in person class.

Result

<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>



The above is the content of XML (6) Write an xml serializer yourself, more For related content, please pay attention to the PHP Chinese website (www.php.cn)!




Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn