最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

簡單實體類和xml文件的相互轉(zhuǎn)換方法

 更新時間:2017年08月24日 08:18:39   投稿:jingxian  
下面小編就為大家?guī)硪黄唵螌嶓w類和xml文件的相互轉(zhuǎn)換方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

最近寫一個題目,要求將一組員工實體類轉(zhuǎn)換成xml文件,或?qū)ml文件轉(zhuǎn)換成一組實體類。題目不難,但寫完感覺可以利用泛型和反射將任意一個實體類和xml文件進行轉(zhuǎn)換。于是今天下午立馬動手

試了下,做了個簡單的模型,可以將簡單的實體類和xml文件進行相互轉(zhuǎn)換,但對實體類的屬性類型有限制,目前只支持String, Integer, Double三種類型。但是后面可以擴展。

我的大概思路是這樣的,只要能拿到實體類的類型信息,我就能拿到實體類的全部字段名稱和類型,拼屬性的set和get方法更是簡單明了,這時候只需要通過方法的反射,將xml文件的數(shù)據(jù)讀取出來給這個反射即可。

反過來只要給我一個任意對象,我就能通過反射拿到該對象所有字段的值,這時候在寫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;
 }
 
 /**
  * 將一組對象數(shù)據(jù)轉(zhuǎn)換成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();
   }
  }
 }
 /**
  * 通過一個根節(jié)點來寫對象的xml節(jié)點,這個方法不對外開放,主要給writeXML(List<T> list, String filePath)提供服務(wù)
  * @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;
 }
 
 /**
  * 默認(rèn)使用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文件轉(zhuǎn)變成實體類
  * @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;
 }
 
 
 /**
  * 將一種類型 和對應(yīng)的 xml元素節(jié)點傳進來,返回該類型的對象,該方法不對外開放
  * @param c 類類型
  * @param ele 元素節(jié)點
  * @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();
   }
  }
 }
 
 /**
  * 默認(rèn)使用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文件,才能轉(zhuǎn)換成實體類,要求是實體類的類類型信息(Class)必須要獲得到。

另外這里的實體類的屬性類型均是Integer,String,Double,可以看到工具類里只對這三種類型做了判斷。而且可以預(yù)想的是,如果出現(xiàn)一對多的關(guān)系,即一個實體類擁有一組另一個類對象的引用,

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

以上這篇簡單實體類和xml文件的相互轉(zhuǎn)換方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 利用Ajax檢測用戶名是否被占用的完整實例

    利用Ajax檢測用戶名是否被占用的完整實例

    這篇文章主要給大家介紹了關(guān)于如何利用Ajax檢測用戶名是否被占用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • javascript Ajax獲取遠(yuǎn)程url的返回判斷

    javascript Ajax獲取遠(yuǎn)程url的返回判斷

    將以下文本放入一個HTML頁面即可看到效果,將會有兩次彈出提示,最后在頁面上顯示YES,表示完成
    2012-01-01
  • JQuery ajax中error返回錯誤及一直返回error的解答

    JQuery ajax中error返回錯誤及一直返回error的解答

    本文由腳本之家小編給大家分享有關(guān) JQuery ajax中error返回錯誤及一直返回error的解答總結(jié),需要的朋友可以參考下
    2015-09-09
  • Ajax全局加載框(Loading效果)的配置

    Ajax全局加載框(Loading效果)的配置

    這篇文章主要介紹了Ajax全局加載框(Loading效果)的配置的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-07-07
  • AJAX在GB2312的中文編碼傳輸 AJAX特殊字符編碼正確方法

    AJAX在GB2312的中文編碼傳輸 AJAX特殊字符編碼正確方法

    此文章為個人總結(jié),花了近半天時間搜索、試驗,在網(wǎng)上看到很多關(guān)于AJAX編碼問題,不一而足
    2010-01-01
  • 解決ajax請求后臺,有時收不到返回值的問題

    解決ajax請求后臺,有時收不到返回值的問題

    今天小編就為大家分享一篇解決ajax請求后臺,有時收不到返回值的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-08-08
  • Ajax商品分類三級聯(lián)動的簡單實現(xiàn)(案例)

    Ajax商品分類三級聯(lián)動的簡單實現(xiàn)(案例)

    下面小編就為大家?guī)硪黄狝jax商品分類三級聯(lián)動的簡單實現(xiàn)(案例)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-08-08
  • Ajax實現(xiàn)步驟和原理解析

    Ajax實現(xiàn)步驟和原理解析

    Ajax是一種用于創(chuàng)建快速動態(tài)網(wǎng)頁的技術(shù),Ajax的工作原理相當(dāng)于在用戶和服務(wù)器之間加了—個中間層(AJAX引擎),使用戶操作與服務(wù)器響應(yīng)異步化,這篇文章主要介紹了Ajax實現(xiàn)步驟和原理,需要的朋友可以參考下
    2023-11-11
  • 基于Jquery.history解決ajax的前進后退問題

    基于Jquery.history解決ajax的前進后退問題

    本文主要給大家介紹基于Jquery.history解決ajax的前進后退問題,涉及到j(luò)query前進后退相關(guān)方面的知識,本文內(nèi)容經(jīng)典,非常具有參考價值,特此把jquery前進后退相關(guān)知識分享在腳本之家網(wǎng)站供大家參考
    2015-10-10
  • ajax實現(xiàn)服務(wù)器與瀏覽器長連接的功能

    ajax實現(xiàn)服務(wù)器與瀏覽器長連接的功能

    這篇文章主要介紹了ajax實現(xiàn)服務(wù)器與瀏覽器長連接的功能的相關(guān)資料,感興趣的小伙伴們可以參考一下
    2016-04-04

最新評論

轮台县| 丰城市| 榆林市| 吉林省| 青阳县| 西乌| 乐都县| 萨嘎县| 从化市| 景东| 德州市| 汉沽区| 安化县| 班戈县| 孝感市| 大冶市| 册亨县| 拉萨市| 麻阳| 绥滨县| 乌苏市| 康定县| 鲁甸县| 台北县| 友谊县| 镇康县| 兴海县| 云安县| 汤原县| 甘孜| 沾益县| 建德市| 西青区| 德江县| 阜宁县| 霍城县| 登封市| 视频| 桂林市| 满城县| 乐清市|