First, write the file one. XML with the following content:
<A>
<B>
<C1>
<First ID = "1" name = '"One">
<First ID = "2" name = '"two">
<First ID = "31" name = '"three">
</C1>
<C2>
# Similar to the first
</C2>
</B>
</A>
Second: Write a class first. Java, which has two Property IDs and names, and then get and set methods.
Third: Write another class as test. java. Write the main method.
Saxreader = new saxreader ();
URL realurl = ratecontext. Class. getclassloader (). getresource ("\ one. xml ");
Document Doc;
Try {
Doc = saxreader. Read (realurl );
List <first> List = new arraylist <first> ();
String Path = "/a/B/C1 ";
List <first> list1 = RC. addele (path, list, first. Class, DOC );;
For (INT I = 0; I <list1.size (); I ++ ){
System. Out. println (list1.get (I). GETID () + "," + list1.get (I). getname ());
}
} Catch (incluentexception e ){
E. printstacktrace ();
}
Fourth: write two methods in test. java.
Public static list addele (string XPath, list, class clazz, document DOC ){
List <element> info = xmlhelper. parsexmlelebyxpath (Doc, XPath );
Field [] fields = clazz. getdeclaredfields ();
For (Element E: INFO ){
Try {
Object object = clazz. newinstance ();
For (field: fields ){
Method method = clazz. getmethod ("set"
+ Touppercase (field. getname (), field. GetType ());
If (field. GetType (). getname (). Equals ("int ")){
Method. Invoke (object, new object [] {INTEGER. parseint (E. attributevalue (Field
. Getname ()))});
} Else {
Method. Invoke (object, new object [] {e. attributevalue (Field
. Getname ())});
}
}
List. Add (object );
} Catch (securityexception E1 ){
Logger.info (e1.getmessage (), E1 );
} Catch (nosuchmethodexception E2 ){
Logger.info (e2.getmessage (), E2 );
} Catch (illegalargumentexception E3 ){
Logger.info (e3.getmessage (), E3 );
} Catch (illegalaccessexception E4 ){
Logger.info (e4.getmessage (), E4 );
} Catch (invocationtargetexception E5 ){
Logger.info (e5.getmessage (), E5 );
} Catch (instantiationexception E6 ){
Logger.info (e6.getmessage (), E6 );
}
}
Return list;
}
Public static string touppercase (string word ){
Return word. substring (0, 1). touppercase () + word. substring (1 );
}
Finally, you can run the project and print it out,
1, one
2, two
3, three