[Continued] C # Use reflection to get attributes and then create an XML document

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.