執行個體詳解簡單實體類和xml檔案的相互轉換方法

來源:互聯網
上載者:User
本文主要為大家帶來一篇簡單實體類和xml檔案的相互轉換方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望能協助到大家。大概思路是這樣的,只要能拿到實體類的類型資訊,我就能拿到實體類的全部欄位名稱和類型,拼屬性的set和get方法更是簡單明了,這時候只需要通過方法的反射,將xml檔案的資料讀取出來給這個反射即可。反過來只要給我一個任意對象,我就能通過反射拿到該對象所有欄位的值,這時候在寫xml檔案即可。

具體代碼如下:

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();  /**  * 判斷是否是個xml檔案,目前類裡尚未使用該方法  * @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; }  /**  * 將一組對象資料轉換成XML檔案  * @param list  * @param filePath 存放的檔案路徑  */ 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.printStackTrace();   }  } } /**  * 通過一個根節點來寫對象的xml節點,這個方法不對外開放,主要給writeXML(List<T> list, String filePath)提供服務  * @param root  * @param object  * @return  * @throws NoSuchMethodException  * @throws SecurityException  * @throws IllegalAccessException  * @throws IllegalArgumentException  * @throws InvocationTargetException  */ private static Element writeXml(Element root, Object object) 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; }  /**  * 預設使用utf-8  * @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"); } /**  * 將一個xml檔案轉變成實體類  * @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> 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; }   /**  * 將一種類型 和對應的 xml元素節點傳進來,返回該類型的對象,該方法不對外開放  * @param c 類類型  * @param ele 元素節點  * @return 該類型的對象  * @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 InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {  Field[] fields = c.getDeclaredFields();  Object object = c.newInstance();//  for(Field f : fields) {   String type = f.getType().toString();//獲得欄位的類型   String fieldName = f.getName();//獲得欄位名稱   String param = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);//把欄位的第一個字母變成大寫   Element e = ele.element(fieldName);   if(type.indexOf("Integer") > -1) {//說明該欄位是Integer類型    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);//通過反射給該欄位set值   }   if(type.indexOf("Double") > -1) { //說明該欄位是Double類型    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) {//說明該欄位是String類型    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; } /**  * 用來寫xml檔案  * @param doc Document對象  * @param filePath 產生的檔案路徑  * @param encoding 寫xml檔案的編碼  */ public static void writeXml(Document doc, String filePath, String encoding) {  XMLWriter writer = null;  OutputFormat format = OutputFormat.createPrettyPrint();  format.setEncoding(encoding);// 指定XML編碼    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();   }  } }  /**  * 預設使用utf-8的格式寫檔案  * @param doc  * @param filePath  */ public static void writeXml(Document doc, String filePath) {  writeXml(doc, filePath, "utf-8"); }}

假如有個實體類是:

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; } }

那麼寫出來的xml檔案格式如下:

<?xml version="1.0" encoding="utf-8"?><emps> <emp> <id>1</id> <name>張三</name> <deptNo>50</deptNo> <age>25</age> <gender>男</gender> <bossId>6</bossId> <salary>9000.0</salary> </emp> <emp> <id>2</id> <name>李四</name> <deptNo>50</deptNo> <age>22</age> <gender>女</gender> <bossId>6</bossId> <salary>8000.0</salary> </emp></emps>

假如有個實體類如下:

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; } }

那麼寫出來的xml檔案如下

<?xml version="1.0" encoding="utf-8"?><students> <student> <id></id> <name>pcq</name> <age>18</age> <gender>男</gender> </student></students>

讀取也必須讀這種格式的xml檔案,才能轉換成實體類,要求是實體類的類類型資訊(Class)必須要獲得到。

另外這裡的實體類的屬性類型均是Integer,String,Double,可以看到工具類裡只對這三種類型做了判斷。而且可以預想的是,如果出現一對多的關係,即一個實體類擁有一組另一個類對象的引用,

那xml和實體類的相互轉換要比上述的情況複雜的多。lz表示短時間內甚至長時間內也不一定能做的出來,歡迎同道高人指點。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.