I. Generate XML documents through object
1. The object must be familiar with and be of the Public type. For example, the following person class
Public Class Person
{
Public String Id { Get ; Set ;}
Public String Name { Get ;Set ;}
Public String Age { Get ; Set ;}
Public String Sex { Get ; Set ;}
}
2. Get a familiar name through reflection and convert it to lowercase letters. At the same time, use the relevant classes in the system. xml namespace to create an XML document.
Public Static Void Createxmlbymodel (list < Object > List, String Filename, String Encode)
{
String Root = Null ;
If (List. Count> 0 )
{
Type P = list [ 0 ]. GetType ();
Root = P. Name. tolower () + " S " ;
}
Xmldocument Doc = New Xmldocument ();
Xmldeclaration dec = Doc. createxmldeclaration ( " 1.0 " , Encode, " Yes " );
Doc. appendchild (DEC );
Xmlelement rootelement = Doc. createelement (Root );
Doc. appendchild (rootelement );
// Add a subnode
Foreach (Object item In List)
{
Xmlelement E = Doc. createelement (item. GetType (). Name. tolower ());
Propertyinfo [] Pi = item. GetType (). getproperties ();
Int I = 0 ;
Foreach (Propertyinfo pro In Pi)
{
Xmlelement child = Doc. createelement (PRO. Name. tolower ());
Child. innertext = pro. getvalue (item, Null ). Tostring ();
E. appendchild (child );
I ++;
}
Rootelement. appendchild (E );
}
Doc. Save (filename );
}
2. Obtain the object set based on the XML document (the object corresponds to the above) Public Static List <person getmodelsfromxml ( String File)
{
List <person list = Null ;
If (File. exists (File ))
{
List = New List <person ();
// Parse XML
Xmldocument Doc = New Xmldocument ();
Doc. Load (File );
Type type = Typeof (Person );
String root = type. Name. tolower () + " S " ;
Xmlnode rootnode = Doc. selectsinglenode (Root );
Xmlnodelist nodes = rootnode. childnodes;
Foreach (Xmlnode item In Nodes)
{
Person = New Person ();
Propertyinfo [] Pi = type. getproperties ();
Xmlnodelist Childs = item. childnodes;
// Traverse subnodes
For ( Int I = 0 ; I <Childs. Count; I ++)
{
Xmlnode n = Childs [I];
// Find the same node name in the property name and XML document, and set the property value
List PS = pi. Where (P => P. Name. tolower () = n. Name). tolist ();
PS [ 0 ]. Setvalue (person, N. innertext. tostring (), Null );
}
List. Add (person );
}
}
Return List;
}
III: If you can rebuild the getmodelsfromxml method, it is suitable for a variety of entities. If you change the person in it to an object, you will be able to perform the perfect operation. However, if you fail to perform the operation, I wonder which hero can give you some advice ..