These two days, should be required to do a small program C/s, considering that the program is concise and small, the way to save data does not use the database, but directly into the XML document saved. You can use the reflection mechanism of C # to do a simple generic tool class.
Implementing the Class Code:
usingSystem;usingSystem.Reflection;usingSystem.Xml.Linq;namespacemytool{ Public Static classObjecttoxml { Public Static stringPath {Get{returnString.Format (@"{0}/{1}.xml", environment.currentdirectory,datetime.now.day.tostring ()); } } Public Static voidIntit (Objectob) {XDocument doc=NewXDocument (NewXdeclaration ("1.0","Utf-8","Yes"), NewXElement ("Data"));//set up with nodes <Data></Data>Process (Ob,doc. Element ("Data")); Doc. Save (Path); } Private Static voidProcess (Objectob,xelement Doc) {XElement Data=Doc; stringClassName =ob. GetType (). Name; Data. ADD (NewXElement (ClassName));//Add a node to a class namepropertyinfo[] Properties= ob. GetType (). GetProperties (BindingFlags.Instance |bindingflags.public); foreach(varIteminchproperties) { stringType =item. GetValue (OB). GetType (). Name; if(Type. ToLower () = ="string"|| Type. ToLower () = ="Int32"|| Type. ToLower () = ="Double")//determines whether a property is a basic type, such as Strin int double if, the node is established and assigned a value{XElement Childnode=data. Element (ClassName); Childnode.add (NewXElement (item. Name, item. GetValue (OB))); } Else //Otherwise, run the process function recursively{Process (item. GetValue (OB), data. Element (ClassName)); } } } }}
View Code
Use:
usingSystem;usingMytool;namespacexmltest{classProgram {Static voidMain (string[] args) { varA =NewStudent {Name="Memeda", age =Ten, gg=1.5, more=NewInfo { Boy="nan", MoreInfo=Newmoreinfo {mv="MV" } } }; Objecttoxml.intit (a); Console.readkey (); } } Public classStudent { Public stringName {Get;Set; } Public intAge {Get;Set; } Public DoubleGG {Get;Set; } PublicInfo more {Get;Set; } } Public classInfo { PublicMoreInfo MoreInfo {Get;Set; } Public stringBoy {Get;Set; } } Public classMoreInfo { Public stringMV {Get;Set; } }}
The final effect:
C # entity classes go into XML