C # object classes are serialized into XML,
In the past two days, a small C/S program should be required. Considering that the program is simple and small, the data storage method does not use the database, but is saved directly to the XML document for storage. To store attributes in complex object classes into XML, we can use the reflection mechanism of C # To implement a simple generic tool class. (Set the property to public)
Is this serialization true? If I make a mistake, remember to remind me (⊙ v ⊙)
Implementation Code:
Using System; using System. reflection; using System. xml. linq; namespace MyTool {public static class ObjectToXml {public static string Path {get {return String. format (@ "{0}/{1 }. xml ", Environment. currentDirectory, DateTime. now. day. toString () ;}} public static void Intit (object ob) {XDocument doc = new XDocument (new XDeclaration ("1.0", "UTF-8", "yes "), new XElement ("Data"); // create a connection node <Data> </Data> Process (ob, doc. element ("Data"); doc. save (Path);} private static void Process (object ob, XElement doc) {XElement data = doc; string ClassName = ob. getType (). name; data. add (new XElement (ClassName); // use the class name to Add a node PropertyInfo [] properties = ob. getType (). getProperties (BindingFlags. instance | BindingFlags. public); foreach (var item in properties) {string type = item. getValue (ob ). getType (). name; if (type. toLower () = "string" | type. toLower () = "int32" | type. toLower () = "double") // determines whether the attribute is of the basic type. For example, if strin int double is used, create a node and assign the value {XElement ChildNode = data. element (ClassName); ChildNode. add (new XElement (item. name, item. getValue (ob);} else // otherwise, recursively run the Process function {Process (item. getValue (ob), data. element (ClassName ));}}}}}View Code
Usage:
using System;using MyTool;namespace xmltest{ class Program { static void Main(string[] args) { var a = new student { Name = "memeda", age = 10,gg=1.5, more=new info { boy="nan", moreinfo=new moreinfo { mv="mv" } } }; ObjectToXml.Intit(a); Console.ReadKey(); } } public class student { public string Name { get; set; } public int age { get; set; } public double gg { get; set; } public info more { get; set; } } public class info { public moreinfo moreinfo { get; set; } public string boy { get; set; } } public class moreinfo { public string mv { get; set; } }}
Final effect: