Example of a simple entity class and XML file conversion method

Source: Internet
Author: User
This article mainly brings a simple entity class and XML file to the mutual conversion method. Small series feel very good, now share to everyone, also for everyone to make a reference. Follow the small series together to see it, hope to help everyone. The idea is that, as long as you can get the type information of the entity class, I can get all the field names and types of the entity class, the set and get method of the spell attribute is more simple and clear, this time only need to pass the reflection of the method, the XML file data read out to this reflection can. In turn, just give me an arbitrary object, I can get the value of all the fields of the object by reflection, and then write the XML file.

The specific code is as follows:

Package Com.pcq.entity;import Java.io.*;import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.util.ArrayList;import Java.util.iterator;import Java.util.list;import Org.dom4j.document;import Org.dom4j.documentexception;import Org.dom4j.documenthelper;import Org.dom4j.element;import Org.dom4j.io.outputformat;import Org.dom4j.io.SAXReader; Import Org.dom4j.io.xmlwriter;public class Xmlandentityutil {private static document document =  Documenthelper.createdocument (); /** * Determines whether it is an XML file, the method is not currently used in the class * @param filePath * @return */@SuppressWarnings ("unused") private static Boolean Isxml  File (String filePath) {File File = new file (FilePath);  if (!file.exists () | | filepath.indexof (". xml") >-1) {return false; } return true; /** * Convert a set of object data to an XML file * @param list * @param filePath file path */public static <T> void WriteXML (List<t&gt ; List, String FilePath) {class<?> c = list.get (0). getclass();  String root = C.getsimplename (). toLowerCase () + "s";  Element Rootele = document.addelement (root);    for (Object obj:list) {try {Element e = writeXml (Rootele, obj);    Document.setrootelement (e);   WRITEXML (document, FilePath); } catch (Nosuchmethodexception | SecurityException | illegalaccessexception | IllegalArgumentException |   InvocationTargetException e) {e.printstacktrace (); }}}/** * The XML node of the object is written through a root node, this method is not open to the outside, mainly to WriteXml (list<t> List, String filePath) service * @param root * @param ob  ject * @return * @throws nosuchmethodexception * @throws SecurityException * @throws illegalaccessexception * @throws IllegalArgumentException * @throws invocationtargetexception */private static Element writeXml (Element root, Object ob ject) throws Nosuchmethodexception, SecurityException, Illegalaccessexception, IllegalArgumentException,  invocationtargetexception {class<?> c = object.getclass (); String className = C.getsimplename (). toLowerCase();  Element ele = root.addelement (className);  field[] fields = C.getdeclaredfields ();   for (Field f:fields) {String fieldName = F.getname ();   String param = fieldname.substring (0, 1). toUpperCase () + fieldname.substring (1);   Element fieldelement = ele.addelement (fieldName);   Method m = C.getmethod ("get" + param, NULL);   String s = "";   if (M.invoke (object, NULL)! = NULL) {s = M.invoke (object, NULL). ToString ();  } fieldelement.settext (s); } return root; }/** * Default use UTF-8 * @param c * @param filePath * @return * @throws unsupportedencodingexception * @throws FILENOTFO Undexception */public static <T> list<t> Getentitys (class<t> C, String FilePath) throws Unsupportedenc Odingexception, FileNotFoundException {return Getentitys (c, FilePath, "Utf-8");}/** * Transforms an XML file into an entity class * @param c * @ Param FilePath * @return * @throws filenotfoundexception * @throws unsupportedencodingexception */public static &LT ; T> list<t> Getentitys (Class<T> C, String FilePath, String encoding) throws Unsupportedencodingexception, filenotfoundexception {File File = N  EW File (FilePath);  String labelname = C.getsimplename (). toLowerCase ();  Saxreader reader = new Saxreader ();   list<t> list = null;   try {inputstreamreader in = new InputStreamReader (new FileInputStream (file), encoding);   Document document = Reader.read (in);   Element root = Document.getrootelement ();   List elements = root.elements (labelname);   List = new arraylist<t> (); for (iterator<emp> it = Elements.iterator (); It.hasnext ();)     {element e = (Element) It.next ();     T t = getentity (c, E);    List.add (t);  }} catch (Documentexception e) {e.printstacktrace ();  } catch (Instantiationexception E1) {e1.printstacktrace ();  } catch (Illegalaccessexception E1) {e1.printstacktrace ();  } catch (Nosuchmethodexception E1) {e1.printstacktrace ();  } catch (SecurityException E1) {e1.printstacktrace (); } catch (Illegalargumentexception E1) {e1.printstacktrace ();  } catch (InvocationTargetException E1) {e1.printstacktrace (); } return list; }/** * a type and corresponding XML element node is passed in, returning an object of that type, which is not open to the outside * @param class C type * @param ele element Node * @return object of that type * @throws Instant  Iationexception * @throws illegalaccessexception * @throws nosuchmethodexception * @throws SecurityException * @throws IllegalArgumentException * @throws invocationtargetexception */@SuppressWarnings ("unchecked") private static <t&gt ; T getentity (class<t> C, Element ele) throws Instantiationexception, Illegalaccessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, invocationtargetexception {Field[] fields =  C.getdeclaredfields (); Object object = C.newinstance ();//For (Field f:fields) {String type = F.gettype (). toString ();//Gets the type of the field String Fiel Dname = F.getname ();//Gets the field name String param = fieldname.substring (0, 1). toUpperCase () + fieldname.substring (1);//The first word of the field The mother becomes the capital Element e = ele.element (fielDNAME);    if (Type.indexof ("Integer") >-1) {//indicates that the field is an integer type integer i = null;    if (E.gettexttrim () = null &&!e.gettexttrim (). Equals ("")) {i = Integer.parseint (E.gettexttrim ());    } Method m = C.getmethod ("set" + param, integer.class);    M.invoke (object, I);//By Reflection to the field set value} if (Type.indexof ("Double") >-1) {//Description The field is double type Double d = null;    if (E.gettexttrim () = null &&!e.gettexttrim (). Equals ("")) {d = double.parsedouble (E.gettexttrim ());    } Method m = C.getmethod ("set" + param, double.class);   M.invoke (object, D);    } if (Type.indexof ("string") >-1) {//indicates that the field is a string of type string s = null;    if (E.gettexttrim () = null &&!e.gettexttrim (). Equals ("")) {s = E.gettexttrim ();    } Method m = C.getmethod ("set" + param, string.class);   M.invoke (object, s); }} return (T) object; }/** * Used to write XML file * @param doc Document Object * @param filePath generated file path * @param encoding write the encoding of the XML file */public static void WriteXml(Document doc, String FilePath, String encoding)  {XMLWriter writer = null;  OutputFormat format = Outputformat.createprettyprint ();   format.setencoding (encoding);//Specify XML encoding try {writer = new XMLWriter (new FileWriter (FilePath), format);  Writer.write (DOC);  } catch (IOException e) {e.printstacktrace ();   } finally {try {writer.close ();   } catch (IOException e) {e.printstacktrace (); }}}/** * default write file in utf-8 format * @param doc * @param filePath */public static void WriteXml (document DOC, String Filep ATH) {writeXml (doc, FilePath, "Utf-8");}}

If there is an entity class that is:

Package Com.pcq.entity;import Java.io.serializable;public class EMP implements serializable{private Integer ID; private String name; Private Integer DeptNo; Private Integer age; Private String gender; Private Integer Bossid; Private Double salary; Public Integer GetId () {return ID,} public void SetId (Integer id) {this.id = ID,} public String GetName () {return Name public void SetName (String name) {this.name = name,} public Integer Getdeptno () {return deptNo;} public void Setde   Ptno (integer deptNo) {this.deptno = DeptNo;} public Integer Getage () {return age,} public void Setage (integer age) { This.age = age; Public String Getgender () {return gender,} public void Setgender (String gender) {This.gender = gender;} public Int Eger Getbossid () {return bossid;} public void Setbossid (Integer bossid) {this.bossid = Bossid;} public Double Getsal ary () {return salary;} public void Setsalary (Double salary) {this.salary = salary;}}

The XML file format that is written is as follows:

<?xml version= "1.0" encoding= "Utf-8"?><emps> <emp> <id>1</id> <name> Zhang San </name > <deptNo>50</deptNo> <age>25</age> <gender> men </gender> <bossid>6</ bossid> <salary>9000.0</salary> </emp> <emp> <id>2</id> <name> John Doe </ name> <deptNo>50</deptNo> <age>22</age> <gender> women </gender> <bossid>6 </bossId> <salary>8000.0</salary> </emp></emps>

If there is an entity class as follows:

Package Com.pcq.entity;public class Student {private integer id; private string name; private integer age; private string Gender Public Integer getId () {  return ID,} public void SetId (Integer id) {  this.id = ID,} public String GetName () {
  return name; public void SetName (String name) {  this.name = name;} public Integer getage () {  return age;} public void Setag E (Integer age) {  This.age = age,} public String Getgender () {  return gender,} public void Setgender (String gende R) {  this.gender = gender;}}

So the XML file is written as follows

<?xml version= "1.0" encoding= "Utf-8"?><students> <student> <id></id> <NAME>PCQ </name> <age>18</age> <gender> men </gender> </student></students>

The read must also read the XML file in this format before it can be converted into an entity class, requiring that the class type information (Class) of the entity class be obtained.

In addition, the attribute types of the entity classes here are integer,string,double, and you can see that only the three types are judged in the tool class. And it can be expected that if there is a one-to-many relationship where an entity class has a reference to another set of class objects,

The transformation of XML and entity classes is much more complex than the above. LZ said that in a short time or even a long time may not be able to do it, welcome fellow expert guidance.

Related Article

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.