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