XML (6) write an xml serializer by yourself

Source: Internet
Author: User
The previous article introduced how to write content to xml files through the serializer. Here we still use the person class for writing. The previous article introduced how to write content to xml files through the serializer. Here we still use the person class for writing.

1. first write a person object
person p=new person() {Name = "istari", Age = 22, Email = "1061399756@qq.com"};
2. then write a method to serialize this object in our way. reflection is used here.
MySerialize(p, typeof(person));
3. write your own serializer in this method


Private static void MySerialize (object obj, Type type) {// Create an XDocument object XDocument document = new XDocument (); // write the xml file, use the class name as the root node string nsStr = type. toString (); string className = nsStr. substring (nsStr. lastIndexOf ('. ') + 1); // write the root node XElement rootElement = new XElement (className); // obtain all the properties of the current type PropertyInfo [] properties = type. getProperties (); // traverse foreach (PropertyInfo item in properties) {rootElement. setElementValue (item. name, item. getValue (obj, null);} document. add (rootElement); document. save (className + ". xml ");}

Reflection is used to obtain all attributes of the person class.

Result
 
   
  
   istari
    22  
  
   1061399756@qq.com
  
 



The above is the content of an XML serializer written by myself in xml (6). For more information, see PHP Chinese network (www.php1.cn )!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.