利用dom4j解析和生成xml格式数据
依赖的jar包:dom4j-1.6.1.jar
实现途径:将数据库中emp表中的数据导入document对象, 然后将document对象写入XML文件;也可以将XML文件解析成document对象,进而从document对象中获取节点信息。
数据库中emp表:
1. 将数据库中表信息存入list中:
GetEmpList.java(将数据库中的数据存入List<EmpInfo>对象中)
package com.nns.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.nns.util.DBConnection;
import com.nns.bean.EmpInfo;
public classGetEmpList {
public List<EmpInfo> getEmpList(){
List<EmpInfo> list = newArrayList<EmpInfo>();
DBConnection dbconn = newDBConnection();
Connection conn = dbconn.getConnection();
String sql = "select empno,enamefrom emp";
try {
Statement st =conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
EmpInfo ei = new EmpInfo();
ei.setEmpno(rs.getInt("empno"));
ei.setEname(rs.getString("ename"));
list.add(ei);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
用到以下两个辅助类:
EmpInfo.java(1)
package com.nns.bean;
public class EmpInfo {
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
publicvoid setEname(String ename) {
this.ename = ename;
}
private int empno;
private String ename;
}
DBConnection.java(数据源获取数据库连接)(2)
package com.nns.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConnection {
privateConnection conn=null;
publicConnection getConnection(){
try{
Contextctx = new InitialContext();
ContextnameingSpaceContext = (Context)ctx.lookup("java:comp/env");
DataSourceds = (DataSource)nameingSpaceContext.lookup("jdbc/user1DataSource");
try{
conn= ds.getConnection();
}catch (SQLException e) {
e.printStackTrace();
}
}catch (NamingException e) {
e.printStackTrace();
}
returnconn;
}
}
2. xml格式数据的生成和解析类(使用dom4j)
Dom4JImpl.java
package com.nns.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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;
importcom.nns.bean.EmpInfo;
public classDom4JImpl {
public void createXMLFile(String filename){
GetEmpList gel = new GetEmpList();
List<EmpInfo> list =gel.getEmpList();
Document document =DocumentHelper.createDocument();
Element root =document.addElement("root");
Element employees =root.addElement("employees");
for(int i=0;i<list.size();i++){
Element employee =employees.addElement("employee");
Element empno =employee.addElement("empno");
Element ename =employee.addElement("ename");
empno.setText(String.valueOf(list.get(i).getEmpno()));
ename.setText(list.get(i).getEname());
}
OutputFormat format =OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
try {
XMLWriter xmlWriter = newXMLWriter(new FileWriter(new File(filename)),format);
xmlWriter.write(document);
xmlWriter.close();
System.out.println("创建xml文件成功");
} catch (IOException e) {
e.printStackTrace();
}
}
public List<EmpInfo> parseXML(Stringfilename){
//System.out.println(filename);
List<EmpInfo> list = newArrayList<EmpInfo>();
File file = new File(filename);
SAXReader saxReader = new SAXReader();
try {
Document document =saxReader.read(file);
System.out.println(document.asXML());
Element root =document.getRootElement();
for(Iterator iter =root.elementIterator();iter.hasNext();){
Element employees =(Element)iter.next();
for(Iterator j =employees.elementIterator();j.hasNext();){
Element employee =(Element)j.next();
EmpInfo ei = new EmpInfo();
for(Iterator k =employee.elementIterator();k.hasNext();){
Element element =(Element)k.next();
if(element.getName().equalsIgnoreCase("empno")){
ei.setEmpno(Integer.parseInt(element.getText()));
} elseif(element.getName().equalsIgnoreCase("ename")){
ei.setEname(element.getText());
}
}
list.add(ei);
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
return list;
}
}
3. jsp中显示
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<a href="createXML.do">创建xml文件</a>
<a href="parseXML.do">解析xml文件</a>
</body>
</html>
其中,请求用到的Action有以下两个:
CreateXMLAction.java(1)
package com.nns.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.nns.util.Dom4JImpl;
/**
* MyEclipse Struts
* Creation date: 04-01-2013
*
* XDoclet definition:
* @struts.action
*/
public class CreateXMLAction extends Action {
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
Dom4JImpl dom4j = new Dom4JImpl();
dom4j.createXMLFile("d:\\emp.xml");
return null;
}
}
ParseXMLAction.java(2)
package com.nns.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.nns.bean.EmpInfo;
import com.nns.util.Dom4JImpl;
/**
* MyEclipse Struts
* Creation date: 04-01-2013
*
* XDoclet definition:
* @struts.action
*/
public class ParseXMLAction extends Action {
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
Dom4JImpl dom4j = new Dom4JImpl();
List<EmpInfo> list = dom4j.parseXML("d:\\emp.xml");
request.setAttribute("list", list);
System.out.println("数量是:"+list.size());
return mapping.findForward("success");
}
}
4. 显示结果和xml数据
xml数据格式:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<employees>
<employee>
<empno>7369</empno>
<ename>SMITH</ename>
</employee>
<employee>
<empno>7499</empno>
<ename>ALLEN</ename>
</employee>
<employee>
<empno>7521</empno>
<ename>WARD</ename>
</employee>
<employee>
<empno>7566</empno>
<ename>JONES</ename>
</employee>
<employee>
<empno>7654</empno>
<ename>MARTIN</ename>
</employee>
<employee>
<empno>7698</empno>
<ename>BLAKE</ename>
</employee>
<employee>
<empno>7782</empno>
<ename>CLARK</ename>
</employee>
<employee>
<empno>7788</empno>
<ename>SCOTT</ename>
</employee>
<employee>
<empno>7839</empno>
<ename>KING</ename>
</employee>
<employee>
<empno>7844</empno>
<ename>TURNER</ename>
</employee>
<employee>
<empno>7876</empno>
<ename>ADAMS</ename>
</employee>
<employee>
<empno>7900</empno>
<ename>JAMES</ename>
</employee>
<employee>
<empno>7902</empno>
<ename>FORD</ename>
</employee>
<employee>
<empno>7934</empno>
<ename>MILLER</ename>
</employee>
</employees>
</root>
数量是:14