一. 项目名:generateXML, 属于java project.

二. 包结构:src
                  |
                  --david
                         |--invoke
                         |--until
                         |--vo

三. 具体实体类
1)实体

package david.vo;

import org.dom4j.Element;

public class Employee {

 public Employee() {
  super();
  // TODO Auto-generated constructor stub
 }
 private Integer empno;
 private String ename;
 private String job;
 private Integer deptno;
 public Integer getEmpno() {
  return empno;
 }
 public void setEmpno(Integer empno) {
  this.empno = empno;
 }
 public String getEname() {
  return ename;
 }
 public void setEname(String ename) {
  this.ename = ename;
 }
 public String getJob() {
  return job;
 }
 public void setJob(String job) {
  this.job = job;
 }
 public Integer getDeptno() {
  return deptno;
 }
 public void setDeptno(Integer deptno) {
  this.deptno = deptno;
 }
 
 public Employee(Integer empno, String ename, String job, Integer deptno) {
  super();
  this.empno = empno;
  this.ename = ename;
  this.job = job;
  this.deptno = deptno;
 }

}



2)数据源

package david.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DataSource {
 
 Connection conn = null;

 ResultSet rs = null;

 /**
  * get a connection
  *
  * @param driver
  * @param url
  * @param name
  * @param pwd
  * @return
  */
 public Connection getConn(String driver, String url, String name, String pwd) {
  try {
   //load driver
   Class.forName(driver);
   //get a connection
   conn = DriverManager.getConnection(url, name, pwd);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return conn;
 }

 /**
  * close a conn
  *
  * @param conn
  * @param rs
  */
 public void closeConn(Connection conn, ResultSet rs) {
  try {
   if (rs != null) {
    rs.close();
   }
   if (conn != null) {
    conn.close();
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 /**
  * get a Resultset
  *
  * @param conn
  * @param sql
  * @return
  */
 public ResultSet getResultSet(Connection conn, String sql) {
  try {
   Statement state = conn.createStatement();
   rs = state.executeQuery(sql);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return rs;
 }

}


3)配置文件

package david.util;

public class Config {
 /**
  * database driver
  */
  public static final String  dataSource_Driver="oracle.jdbc.driver.OracleDriver";
 
  /**
   *   database url
   */
  public static final String dataSource_url="jdbc:oracle:thin:@127.0.0.1:1521:myorcl";
 
  /**
   * user name
   */
  public static final String dataSource_userName="scott";
 
  /**
   * user password
   */
  public static final String dataSource_password="tiger";
 
  /**
   * employee
   */
  public static final String dataSource_emp_sql="select * from emp_bk";

  /**
   * dept
   */
  public static final String dataSource_dept_sql="select * from dept_bk";
 
}


4)添加节点(employee)生成XML类

 

package david.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import david.vo.Employee;

public class createXml {
 /**
  * every employee element
  * @param emp
  * @return
  */
 public static Element getXML(Employee emp) {
  
  
  Element employee = DocumentHelper.createElement("employee");
  
  Element empno = employee.addElement("empno");
  empno.setText(String.valueOf(emp.getEmpno()));

  Element ename = employee.addElement("ename");
  ename.setText(emp.getEname());

  Element job = employee.addElement("job");
  job.setText(emp.getJob());

  Element deptno = employee.addElement("deptno");
  deptno.setText(String.valueOf(emp.getDeptno()));
  return employee;
 }

 /**
  * test method
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  List<Employee> empList = new ArrayList<Employee>();
  empList.add(new Employee(1001, "david", "developer", 10));
  empList.add(new Employee(1002, "tom", "teacher", 20));
  empList.add(new Employee(1003, "jack", "student", 30));
  empList.add(new Employee(1004, "marry", "driver", 40));

  Element root = DocumentHelper.createElement("employees");
  Document document = DocumentHelper.createDocument();
  document.setRootElement(root);
  for (Employee emp : empList) {
   root.add(createXml.getXML(emp));
  }

  //output format
  OutputFormat format = OutputFormat.createPrettyPrint(); //设置XML文档输出格式
  format.setEncoding("GBK"); //设置XML文档的编码类型
  format.setSuppressDeclaration(true);
  format.setIndent(true); //设置是否缩进
  format.setIndent("   "); //以空格方式实现缩进
  format.setNewlines(true); //设置是否换行
 
  createXml.outPutXML(root, "d:\\test.xml", format);
  
 }
 
 /**
  * writer
  * @param root
  * @param fileName
  * @param format
  * @throws IOException
  * @throws SAXException
  */
 public static void outPutXML(Element root, String fileName, OutputFormat format) throws IOException, SAXException{
  XMLWriter xw = new XMLWriter(new FileWriter(new File(fileName)), format);
  xw.processingInstruction("xml version=\"1.0\"", "encoding=\"GBK\"");
  xw.write(root);
  xw.flush();
  xw.close();
  //System.out.println(root.asXML());
 }
 
 
 

}


5)生成XML的调用类

 

package david.invoke;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.xml.sax.SAXException;

import david.util.Config;
import david.util.DataSource;
import david.util.createXml;
import david.vo.Employee;

public class Xml {

 public static Connection conn = null;

 public static ResultSet rs_dept = null;

 public static ResultSet rs_emp = null;

 public static String deptids = "";

 /**
  * @param args
  * @throws SAXException
  * @throws IOException
  */
 public static void main(String[] args) throws IOException, SAXException {
  DataSource ds = new DataSource();
  // get dept collection
  conn = ds.getConn(Config.dataSource_Driver, Config.dataSource_url,
    Config.dataSource_userName, Config.dataSource_password);
  if (conn != null) {
   rs_dept = ds.getResultSet(conn, Config.dataSource_dept_sql);
  }
  if (rs_dept != null) {
   try {
    while (rs_dept.next()) {
     deptids = deptids + rs_dept.getString("DEPTNO") + ",";
     // System.out.println(deptids);
    }
    ds.closeConn(conn, rs_dept);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  // get emp connection
  List<Employee> empList = new ArrayList<Employee>();

  conn = ds.getConn(Config.dataSource_Driver, Config.dataSource_url,
    Config.dataSource_userName, Config.dataSource_password);
  if (conn != null) {
   rs_emp = ds.getResultSet(conn, Config.dataSource_emp_sql);
  }
  if (rs_emp != null) {
   try {
    while (rs_emp.next()) {
     Employee emp = new Employee();
     emp.setEmpno(rs_emp.getInt("EMPNO"));
     emp.setEname(rs_emp.getString("ENAME"));
     emp.setJob(rs_emp.getString("JOB"));
     emp.setDeptno(rs_emp.getInt("DEPTNO"));

     empList.add(emp);
    }
    ds.closeConn(conn, rs_emp);
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

  // output format
  OutputFormat format = OutputFormat.createPrettyPrint(); // set xml output format
  format.setEncoding("GBK"); // set xml encoding type
  format.setSuppressDeclaration(true);
  format.setIndent(true); // set retractive
  format.setIndent("   "); // set retractive pattern is whilespace
  format.setNewlines(true); // set new line

  //dept
  String[] deids = deptids.split(",");

  for (int i = 0; i < deids.length; i++) {
   //create a root every dept
   Element root = DocumentHelper.createElement("employees");
   Document document = DocumentHelper.createDocument();
   document.setRootElement(root);

   for (Employee emp : empList) {
    if(deids[i].equals(emp.getDeptno().toString())){
     root.add(createXml.getXML(emp));
    }
   }
   
   Iterator it = root.elements("employee").iterator();
   while(it.hasNext()){
    if(it.next()==null){
     continue;         //if no employee in this dept, skip this dept, not create this dept directory.
    }
   File file = new File("d:\\lab\\dept" + deids[i]);
   if (!file.exists()) {
    file.mkdir();
   }
    createXml.outPutXML(root, "d:\\lab\\dept" + deids[i] +"\\emp.xml",format); // create a xml every dept
   }
   
  }

 }

}


 


6)打包类

package david.invoke;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zip {
    static final int BUFFER = 2048;
  
    public static void main(String argv[]) {
        try {
 
            File fRoot = new File("d:\\lab\\");
            File dirRoot[] = fRoot.listFiles();
            if((dirRoot==null)||(!(dirRoot.length>0))){
             System.out.println("please check the directory and it's child directory is exists!");
             return;
            }
            byte data[] = new byte[BUFFER];
            for(int i=0; i<dirRoot.length; i++){
             
                BufferedInputStream origin = null;
                FileOutputStream dest = new FileOutputStream("D:\\lab\\"+dirRoot[i].getName()+".zip");
                ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
         
             File f = new File(dirRoot[i].getPath());
                File files[] = f.listFiles();
               
                for(int j=0; j<files.length; j++){
                    FileInputStream fi = new FileInputStream(files[j]);
                    origin = new BufferedInputStream(fi, BUFFER);
                    ZipEntry entry = new ZipEntry(files[j].getName());
                    out.putNextEntry(entry);
                    int count;
                    while ((count = origin.read(data, 0, BUFFER)) != -1) {
                        out.write(data, 0, count);
                    } 
                    origin.close();
                    }
                out.close();
     
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}