Home > Backend Development > XML/RSS Tutorial > XML (6) Write an xml serializer yourself

XML (6) Write an xml serializer yourself

黄舟
Release: 2017-02-10 16:35:07
Original
1566 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login



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




Related labels:
xml
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template