java利用dom4j对输入的任意对象生成xml文件

最近业务需求要求对集合和pojo对象进行生成xml文件,和对xml的解析,解析xml我以前写过,对于生成还是比较陌生的,近两天自己写了个 ,在真正的使用的时候你必须重载已满足业务需要。下面就是本人最近写的,拿出来分享。

pojo对象文件

package pojo;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

 private String name ;
    private String password;
    private String realName;
    private Integer sex;
    private Integer age;
    private Date birthday;
    private String phone;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getPassword() {
  return password;
 }
 public void setPassword(String password) {
  this.password = password;
 }
 public String getRealName() {
  return realName;
 }
 public void setRealName(String realName) {
  this.realName = realName;
 }
 public Integer getSex() {
  return sex;
 }
 public void setSex(Integer sex) {
  this.sex = sex;
 }
 public Integer getAge() {
  return age;
 }
 public void setAge(Integer age) {
  this.age = age;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 public String getPhone() {
  return phone;
 }
 public void setPhone(String phone) {
  this.phone = phone;
 }
   
   
}

生成主文件

package javaReflect;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import pojo.User;
/**
 *
 *@date Dec 24, 20097:09:05 PM
 *@author zhangjp
 *@param
 */
public class ReflectTest1 {
 
 public ReflectTest1(){
  getClassXML(getObjectData());
 }

  /**
   * 获得list数据
   * @returnReflectTest1.java
   */
 public  List<User> getData(){
  List <User> list = new ArrayList<User>();
     User u1 = new User();
     u1.setName("zhangsan");
     u1.setPassword("123456");
     u1.setRealName("zhangjip");
     u1.setSex(1);
     u1.setAge(22);
     u1.setBirthday(new Date());
     u1.setPhone("123455555555");
    
     User u2 = new User();
     u2.setName("wangwu");
     u2.setPassword("5555");
     u2.setRealName("zhangjip");
     u2.setSex(1);
     u2.setAge(30);
     u2.setBirthday(new Date());
     u2.setPhone("12345588888");
     list.add(u1);
     list.add(u2);
  return list;
 }
 /**
  * 获得object数据
  * @returnReflectTest1.java
  */
 public Object getObjectData(){
    User u1 = new User();
     u1.setName("zhangsan");
     u1.setPassword("123456");
     u1.setRealName("zhangjip");
     u1.setSex(1);
     u1.setAge(22);
     u1.setBirthday(new Date());
     u1.setPhone("123455555555");
     return u1;
 }
 /**
  * object生成
  * @param objReflectTest1.java
  */
 public void getClassXML(Object obj){
  try {
   if (obj == null) {
    return;
   }
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement("kedou");
    String className = obj.getClass().getName();
    String name = className.substring(className.lastIndexOf('.')+1);
    Element element = root.addElement(name);
       Field[] fields = obj.getClass().getDeclaredFields();
  
    for (int j = 0; j < fields.length; j++) {
     fields[j].setAccessible(true);
     if(fields[j].get(obj)==null){
      continue;
     }
     String objValue = fields[j].get(obj).toString();
     String fieldName = fields[j].toString().substring(fields[j].toString().lastIndexOf('.')+1);
     element.addAttribute(fieldName,objValue);
                      MyOutputFormat.createCompactFormat();
     // HttpServletResponse response =
     // ServletActionContext.getResponse();
     // PrintWriter out = response.getWriter();
     // response.setContentType("text/xml;charset=utf-8");
     // response.setHeader("Cache-Control", "no-cache");
     // out.print(document.asXML());
     
    }
    
   writeDocument(document.asXML(),new File("D:\MyXNL"));
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
 }
 

    /**
     * list生成
     * @param listReflectTest1.java
     */
 public void getClassXML(List<?> list){
  try {
   if (list == null || list.size() == 0) {
    return;
   }
   Document document = DocumentHelper.createDocument();
   Element root = document.addElement("kedou");
   for (int i = 0; i < list.size(); i++) {
    String className = list.get(i).getClass().getName();
    String name = className.substring(className.lastIndexOf('.')+1);
    Element element = root.addElement(name);
       Field[] fields = list.get(i).getClass().getDeclaredFields();
  
    for (int j = 0; j < fields.length; j++) {
     fields[j].setAccessible(true);
     if(fields[j].get(list.get(i))==null){
      continue;
     }
     String objValue = fields[j].get(list.get(i)).toString();
     String fieldName = fields[j].toString().substring(fields[j].toString().lastIndexOf('.')+1);
     element.addAttribute(fieldName,objValue);

     // HttpServletResponse response =
     // ServletActionContext.getResponse();
     // PrintWriter out = response.getWriter();
     // response.setContentType("text/xml;charset=utf-8");
     // response.setHeader("Cache-Control", "no-cache");
     // out.print(document.asXML());
     
    }
    
    
   }
   writeDocument(document.asXML(),new File("D:\MyXNL"));
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
 }
 
 
 /**
  * 写xml文件
  * @param str
  * @param file
  * @throws ExceptionReflectTest1.java
  */
 public void writeDocument(String str,File file) throws Exception{
   try {  
      /* StringWriter writer = new StringWriter();  
       OutputFormat format = OutputFormat.createPrettyPrint();  
       format.setEncoding("utf-8");  
       XMLWriter xmlwriter = new XMLWriter(writer, format);  
       xmlwriter.write(str);  
       String outString = writer.toString();   */
      
     OutputStream os = new FileOutputStream(file);
     PrintWriter out = new PrintWriter(new OutputStreamWriter(os,"utf-8"));
     System.out.println(str);
     out.print(str);
     out.flush();
   } catch (Exception ex) {  
         ex.printStackTrace();  
     }
 }
 
 public static void main(String[] args){
  new ReflectTest1();
 }

}

原文地址:https://www.cnblogs.com/alaricblog/p/3278349.html