-
-
-
-
-
-
-
-
-
- public void createXmlDocument(T obj, List<T> entityPropertys, String Encode,
- String XMLPath) {
- try {
- XMLWriter writer = null;
- OutputFormat format = OutputFormat.createPrettyPrint();
- format.setEncoding(Encode);
-
- File file = new File(XMLPath);
-
- if (file.exists()) {
- file.delete();
- }
-
- Document document = DocumentHelper.createDocument();
- String rootname = obj.getClass().getSimpleName();
- Element root = document.addElement(rootname + "s");
- Field[] properties = obj.getClass().getDeclaredFields();
-
- for (T t : entityPropertys) {
- Element element = root.addElement(rootname);
- for (int i = 0; i < properties.length; i++) {
-
- Method meth = t.getClass().getMethod("get"+ properties[i].getName().substring(0, 1).toUpperCase() + properties[i].getName().substring(1));
-
- element.addElement(properties[i].getName()).setText(meth.invoke(t).toString());
- }
- }
- writer = new XMLWriter(new FileOutputStream(file), format);
- writer.write(document);
- writer.close();
- } catch (Exception e) {
- System.out.println("XML文件写入失败");
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
-
-
- public List<T> parserXml(String XMLPath, T t) {
- List<T> list = new ArrayList<T>();
- try {
- File f = new File(XMLPath);
- SAXReader reader = new SAXReader();
- Document doc = reader.read(f);
- Element root = doc.getRootElement();
- Element secondElement;
- Field[] properties = t.getClass().getDeclaredFields();
-
- Method setMethod = null;
- for (Iterator i = root.elementIterator(t.getClass().getSimpleName()); i.hasNext();) {
-
- secondElement = (Element) i.next();
- t = (T)t.getClass().newInstance();
- Object[] args = new Object[properties.length];
- for (int j = 0; j < properties.length; j++) {
-
-
- setMethod = t.getClass().getMethod("set"+ properties[j].getName().substring(0, 1).toUpperCase()+ properties[j].getName().substring(1),properties[j].getType());
- setMethod.invoke(t,secondElement.elementText(properties[j].getName())) ;
- }
- list.add(t);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return list;
- }
-
posted on
2011-12-23 09:51
John Liang
阅读(
503)
评论()
编辑
收藏
举报