The corresponding JavaBean object collection is obtained by using reflection and dom4j read JavaBean to generate corresponding XML and read XML.

Source: Internet
Author: User
Tags xml example

Transferred from: http://blog.csdn.net/zhao19861029/article/details/8473245

First implement the XML file method that generates the corresponding JavaBean

/*** dmo4j Write XML *@paramobj Generic Object *@paramEntitypropertys list collection of generic objects *@paramEncode XML custom encoding type (recommended with GBK) *@paramxmlpathandname the path and file name of the XML file*/       Public voidWritexmldocument (T obj, list<t>Entitypropertys, String Encode, String xmlpathandname) {           Longlasting = System.currenttimemillis ();//Efficiency Testing          Try{XMLWriter writer=NULL;//declaring an object that writes XMLOutputFormat format =Outputformat.createprettyprint (); Format.setencoding (Encode);//to set the encoding format for an XML fileString FilePath= Xmlpathandname;//get the file addressFile File =NewFile (FilePath);//Get Files              if(File.exists ()) {file.delete (); }               //Create a new Student.xml file and add new contentDocument document =documenthelper.createdocument (); String Rootname= Obj.getclass (). Getsimplename ();//Get class nameElement root = document.addelement (Rootname + "s");//Add root nodeField[] Properties = Obj.getclass (). Getdeclaredfields ();//get all properties of an entity class                         for(T T:entitypropertys) {//Recursive entitiesElement secondroot = root.addelement (rootname);//Level Two node                                 for(inti = 0; i < properties.length; i++) {                                          //Reflection Get MethodMethod meth =T.getclass (). GetMethod ("Get" + properties[i].getname (). substring (0, 1). toUpperCase ()+ properties[i].getname (). SUBSTRING (1)); //add an attribute to a level two node with the value of the corresponding propertysecondroot.addelement (Properties[i].getname ()). SetText (Meth.invoke (                     T). toString ()); }               }               //generating an XML filewriter =NewXMLWriter (NewFileWriter (file), format);               Writer.write (document);               Writer.close (); LongLasting2 =System.currenttimemillis (); System.out.println ("Write XML file End, spents" + (lasting2-lasting) + "MS"); } Catch(Exception e) {System.out.println ("XML File Write Failed"); }         }  

Test this method

/*** dom4j Read and write XML example * *@paramargs *@throwsException*/     Public Static voidMain (string[] args) {dom4jtest<User> d =NewDom4jtest<user>(); User User=NewUser (); User User1=NewUser ("Name 1", "18", "Male"); User User2=NewUser ("Name 2", "19", "female"); User User3=NewUser ("Stone", "20", "female"); List<User> users =NewArraylist<user>();       Users.add (user1);       Users.add (User2);         Users.add (USER3); D.writexmldocument (user, users,"GBK", "Webroot\\web-inf\\student.xml"); }  

At this point the resulting XML file is as follows

View Plaincopy to Clipboardprint?<?xml version= "1.0" encoding= "GBK"?>    <Users>    <User>      <name> name 1</name>      <age>18</age>      <sax> men </sax>    </User>    <User>      <name> name 2</name>      <age>19</age>      <sax> women </sax>    </User>    <User>      <name> stone </name>      <age>20</age>      <sax > Women </sax>    </User>  </Users>  

Implementing a method of reading an XML file to get a collection of objects

/**   *    * @paramXmlpathandname the path and address of the XML file *@paramT Generic Object *@return   */@SuppressWarnings ("Unchecked")        PublicList<t>ReadXML (String xmlpathandname, T t) {Longlasting = System.currenttimemillis ();//Efficiency Testinglist<t> list =NewArraylist<t> ();//Create a list collection        Try{File F=NewFile (Xmlpathandname);//Read FileSaxreader reader =NewSaxreader (); Document Doc= Reader.read (f);//dom4j ReadElement root = Doc.getrootelement ();//Get root nodeElement foo;//Level Two nodeField[] Properties = T.getclass (). Getdeclaredfields ();//get the properties of an instance//The Get method of the instanceMethod Getmeth; //the Set method of the instanceMethod Setmeth;  for(Iterator i = Root.elementiterator (T.getclass (). Getsimplename ()); I.hasnext ();) {//traverse the T.getclass (). Getsimplename () nodeFoo = (Element) i.next ();//Next Level Two nodeT= (T) t.getclass (). newinstance ();//get a new instance of an object                  for(intj = 0; J < Properties.length; J + +) {//traverse all grandchild nodes//the Set method of the instanceSetmeth =T.getclass (). GetMethod ("Set" + properties[j].getname (). substring (0, 1). toUpperCase ()+ properties[j].getname (). SUBSTRING (1), Properties[j].gettype ()); //Properties[j].gettype () is the parameter type of the Set method entry parameter (class type)Setmeth.invoke (t, Foo.elementtext (Properties[j].getname ()));//The value of the corresponding node is stored} list.add (t); }           } Catch(Exception e) {e.printstacktrace (); }           LongLasting2 =System.currenttimemillis (); System.out.println ("Read XML file End, spents" + (lasting2-lasting) + "MS"); returnlist; }  

Test:

 Public Static voidMain (string[] args) {dom4jtest<User> d =NewDom4jtest<user>(); User User=NewUser (); List<User> list= d.readxml ("Webroot\\web-inf\\student.xml", user); System.out.println ("XML file Read results");  for(intI =0;i<list.size (); i++) {User usename=(User) list.get (i); System.out.println ("Name" +usename.getname ()); System.out.println ("Age" +usename.getage ()); System.out.println ("Sax" +Usename.getsax ()); }     }  

Console Print Results:

Name Name 1 age18 sax male name Name 2 age19 sax female name stone age20 sax Female

The corresponding JavaBean object collection is obtained by using reflection and dom4j read JavaBean to generate corresponding XML and read XML.

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.