Mutual conversion between simple object classes and xml files, and mutual conversion between object classes xml

Source: Internet
Author: User

Mutual conversion between simple object classes and xml files, and mutual conversion between object classes xml

I recently wrote a question that requires converting a group of employee entity classes into xml files or converting xml files into a group of entity classes. The question is not difficult, but after writing it, you can use generics and reflection to convert any entity class and xml file. So we started this afternoon.

After trying it out, I made a simple model to convert simple object classes and xml files to each other. However, there are restrictions on the attribute types of object classes. Currently, only String, Integer are supported, double. But it can be expanded later.

My general idea is that as long as I can get the type information of the object class, I can get all the field names and types of the object class, the set and get methods for Attribute spelling are simple and clear. In this case, you only need to read the data in the xml file to this reflection through method reflection.

In turn, as long as you give me an arbitrary object, I can get the values of all the fields of the object through reflection. At this time, I can write the xml file.

The 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. extends entexception; import org. dom4j. export enthelper; import org. dom4j. element; import org. dom4j. io. outputFormat; import org. dom4j. io. S AXReader; import org. dom4j. io. XMLWriter; public class XMLAndEntityUtil {private static Document document Document = incluenthelper. createDocument ();/*** determines whether an xml file is used. Currently, this method is not used in the class * @ param filePath * @ return */@ SuppressWarnings ("unused ") private static boolean isXMLFile (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: Path of the file stored in */public static <T> void writeXML (List <T> 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. printStackT Race () ;}}/ *** write the xml node of the object through a root node. This method is not open to the outside, mainly for writeXML (List <T> list, string filePath) provide Services * @ param root * @ param object * @ return * @ throws NoSuchMethodException * @ throws SecurityException * @ throws IllegalAccessException * @ throws limit * @ throws InvocationTargetException */private static Element writeXml (element root, object object) throws NoSuchMethodException, Securit YException, 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 ;} /*** UTF-8 is used by default * @ param c * @ param filePath * @ return * @ throws UnsupportedEncodingException * @ throws FileNotFoundException */public static <T> List <T> getEntitys (Class <T> c, string filePath) throws UnsupportedEncodingException, FileNotFoundException {return getEntitys (c, filePath, "UTF-8 ");}/*** Convert an xml file into an object Class * @ param c * @ param filePath * @ return * @ throws FileNotFoundException * @ throws UnsupportedEncodingException */public static <T> List <T> getEntitys (Class <T> c, string filePath, String encoding) throws UnsupportedEncodingException, FileNotFoundException {File file = new File (filePath); String labelName = c. getSimpleName (). toLowerCase (); SAXReader reader = new SAXReader (); List <T> lis T = 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 (incluentexcep Tion 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 l Ist;}/*** transmits a type and corresponding xml Element Node to return objects of this type, this method is not open to the public * @ param c class type * @ param ele Element Node * @ return object of this type * @ throws InstantiationException * @ throws IllegalAccessException * @ throws NoSuchMethodException * @ throws SecurityException * @ throws IllegalArgumentException * @ throws InvocationTargetException */@ SuppressWarnings ("unchecked ") private static <T> T getEntity (Class <T> c, Element ele) throws Ins TantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {Field [] fields = c. getDeclaredFields (); Object object = c. newInstance (); // for (Field f: fields) {String type = f. getType (). toString (); // obtain the field type String fieldName = f. getName (); // obtain the field name String param = fieldName. substring (0, 1 ). toUpperCase () + fieldName. substr Ing (1); // converts the first letter of the field to uppercase Element e = ele. element (fieldName); if (type. indexOf ("Integer")>-1) {// indicates that this field is of the 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); // returns the set value to this field} if (type. indexOf ("Double")>-1) {// This 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) {// This field is String 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 the xml file * @ param doc Document object * @ param filePath the generated file path * @ param encoding 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 the 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 () ;}}/ *** write a file in UTF-8 format by default * @ param doc * @ param filePath */public static void writeXml (Document doc, String filePath) {writeXml (doc, filePath, "UTF-8 ");}}

Assume that an object class 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 setDeptNo(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 Integer getBossId() {  return bossId; } public void setBossId(Integer bossId) {  this.bossId = bossId; } public Double getSalary() {  return salary; } public void setSalary(Double salary) {  this.salary = salary; } }

The format of the written xml file 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 & gt; male </gender> <bossId> 6 </bossId> <salary> 9000.0 </salary> </emp> <id> 2 </id> <name> li Si </name> <deptNo> 50 </deptNo> <age> 22 </age> <gender> female </gender> <bossId> 6 </bossId> <salary> 8000.0 </salary> </emp> </emps>

Assume that an object class is 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 setAge(Integer age) {  this.age = age; } public String getGender() {  return gender; } public void setGender(String gender) {  this.gender = gender; } }

The written xml file is as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <Students> <student> <id> </id> <name> pcq </name> <age> 18 </age> <gender> male </gender> </student> </students>

To read an xml file in this format, you must read the file to convert it to an object Class. The object Class information must be obtained.

In addition, the attribute types of the object classes are Integer, String, and Double. You can see that only the three types are judged in the tool class. In addition, it can be predicted that if there is a one-to-many relationship, that is, an object class has a reference to a group of other class objects,

The mutual conversion between xml and object classes is much more complex than the preceding situation. Lz indicates that you may not be able to do it in a short time or even a long time.

The method for converting the above simple entity classes and xml files is all the content shared by the editor. I hope to give you a reference and support for the help house.

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.