In the previous article, you need to know the specific object type in method 2 getmodelsfromxml. Later, I found that the object can be used instead. The result is successful. The modification method is as follows:
/// <Summary>
/// Serialize an XML document into an object
/// </Summary>
/// <Param name = "file"> File Path </Param>
/// <Returns> </returns>
Public Static List <Object> getmodelsfromxml ( String File, type)
{
List <Object> List = Null ;
If (File. exists (File ))
{
List = New List <Object> ();
// Parse XML
Xmldocument Doc = New Xmldocument ();
Doc. Load (File );
String root = type. Name. tolower () + " S " ;
Xmlnode rootnode = Doc. selectsinglenode (Root );
Xmlnodelist nodes = rootnode. childnodes;
Foreach (Xmlnode item In Nodes)
{
Object OBJ = type. Assembly. createinstance ( " Toolkit. Person " ); // Note that the name must be a full name.
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 <propertyinfo> PS = pi. Where (P => P. Name. tolower () = n. Name). tolist ();
PS [ 0 ]. Setvalue (OBJ, N. innertext. tostring (), Null );
}
List. Add (OBJ );
}
}
Return List;
}
CalledCodeAs follows:
List < Object > Persons = New List < Object > ();
Persons. addrange ( New Person [] {
New Person () {id = " 1 " , Name = " Jay " , Age = " 23 " , Sex = " Male " },
New Person () {id = " 2 " , Name = " Lucy " , Age = " 20 " , Sex = " Female " },
New Person () {id = " 3 " , Name = " Mike " , Age = " 22 " , Sex = " Male " }});
Toolkit. createxmlbymodel (persons, " C:/users/liyong/desktop/1.xml " , " UTF-8 " );
Persons = toolkit. getmodelsfromxml ( " C:/users/liyong/desktop/1.xml " , Typeof (Person ));
Foreach ( VaR Item In Persons)
{
Console. writeline (item. tostring ());
}
Result output: