import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class CreateXml {
public static String Create() {
// 用工厂类创建一个document实例
Document doc = DocumentHelper.createDocument();
// 创建根元素emps
Element rootEle = doc.addElement("students");
// 添加注释
rootEle.addComment("这是一个dom4j生成的xml文件");
// emps根节点下创建一个emp节点
for (int i = 0; i < 10; i++) {
Element empEle = rootEle.addElement("student");
// emp添加属性id="1"
String id = (i + 1) % 2 == 0 ? Integer.toString(i + 1) : "";
empEle.addAttribute("id", id);
// emp节点下创建一个name节点
Element nameEle = empEle.addElement("name");
// name节点下创建一个文本节点
nameEle.setText("胡秀亮" + i);
String age = (i + 1) % 3 == 0 ? Integer.toString(i + 1) : "";
nameEle.addAttribute("age", age);
Element sexEle = empEle.addElement("sex");
sexEle.setText(i % 2 == 0 ? "男" : "女");
}
return doc.asXML();
// return XmlToString(doc,true);
/**将document中的内容写入文件中
try {
Writer out = new FileWriter("D:/MyTool/Work_Output/emps.xml");
// 格式化输出,类型IE浏览一样
OutputFormat format = OutputFormat.createPrettyPrint();
// OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
// 创建写出对象
XMLWriter writer = new XMLWriter(out, format);
writer.write(doc);
writer.close();
System.out.println("生成emps.xml成功。");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("失败了。");
}
**/
}
/**
* 如果发生中文乱码用此类转换
*
* @param Doc
* @param PrettyPrint
* @return
*/
public static String XmlToString(Document Doc, boolean PrettyPrint) {
String s = "";
StringWriter sw = null;
try {
OutputFormat fmt = null;
if (PrettyPrint) {
fmt = new OutputFormat(" ", true, "GBK");
fmt.setLineSeparator("\r\n");
} else {
fmt = OutputFormat.createCompactFormat();
fmt.setEncoding("GBK");
}
fmt.setNewLineAfterDeclaration(false);
fmt.setExpandEmptyElements(true);
sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw, fmt);
xw.write(Doc);
sw.close();
s = sw.toString();
} catch (Exception ex) {
s = "";
ex.printStackTrace();
} finally {
try {
sw.close();
} catch (Exception ex1) {
}
}
return s;
}
}
///////////////////////////////////////
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 利用dom4j进行XML编程
*
*
*/
public class Dom4jReadExmple {
public static List iterateWholeXML(String url) {
List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(url);
Element root = document.getRootElement();
// 遍历根结点(students)的所有孩子节点(肯定是student节点)
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element element = (Element) iter.next();
HashMap<String, String> hm = new HashMap<String, String>();
// 获取person节点的age属性的值
Attribute ageAttr = element.attribute("id");
if (ageAttr != null) {
String age = ageAttr.getValue();
if (age != null && !age.equals("")) {
hm.put(element.getName() + "_" + ageAttr.getName(), age);
} else {
hm.put(element.getName() + "_" + ageAttr.getName(), "20");
}
} else {
hm.put(element.getName() + "_id", "20");
}
// 遍历student结点的所有孩子节点(即name,college,telphone,notes),并进行处理
for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
Element elementInner = (Element) iterInner.next();
if (elementInner.getName().equals("name")) {
hm.put(elementInner.getName(), elementInner.getText());
// 获取college节点的leader属性的值
Attribute leaderAttr = elementInner.attribute("age");
if (leaderAttr != null) {
String leader = leaderAttr.getValue();
if (leader != null && !leader.equals("")) {
hm.put(elementInner.getName() + "_" + leaderAttr.getName(), leader);
} else {
hm.put(elementInner.getName() + "_" + leaderAttr.getName(), "age");
}
} else {
hm.put(elementInner.getName() + "_age", "age");
}
} else {
hm.put(elementInner.getName(), elementInner.getText());
}
}
list.add(hm);
}
} catch (DocumentException e) {
// TODO Auto_generated catch block
e.printStackTrace();
}
return list;
// return null;
}
}
///////////////////servlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ViewXml extends HttpServlet {
/**
* Constructor of the object.
*/
public ViewXml() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); //
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(CreateXml.Create());
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
////////////////////////
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* 测试Dom4jReadExmple解析的情况
*
*
*/
public class TestDom4jReadExmple {
public static void main(String[] args) {
try {
// 获取解析完后的解析信息
List list = new ArrayList();
// 遍历整个XML文件
list = Dom4jReadExmple.iterateWholeXML("http://localhost:8080/XML/ViewXml");
System.out.println(list.size());
System.out.println("姓名\t学号\t年龄\t性别");
if (list!=null&&list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
HashMap map = (HashMap) list.get(i);
System.out.print(map.get("name") + "\t");
System.out.print(map.get("student_id") + "\t");
System.out.print(map.get("name_age") + "\t");
System.out.println(map.get("sex") + "\t");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* 注意: dom4j1.6
* 解压后有一个dom4j-1.6.1.jar文件,这就是应用时需要引入的类包,另外还有一个jaxen-1.1-beta-6.jarr文件,一般也需要引入,否则执行时可能抛java.lang.NoClassDefFoundError:
* org/jaxen/JaxenException异常,其他的包可以选择用之。
*
*
*/