参考资料:
Dom4j 使用简介
作者:冰云 icecloud(AT)sina.com
http://blog.csdn.net/icecloud/archive/2003/12/17/7795.aspx
dom4j API和源码、例子下载网址:
http://sourceforge.net/project/showfiles.php?group_id=16035
下载dom4j-1.6.1.zip:带源码和例子。
一.dom4j解析xml
这部分内容之前已经写过,作为完整性,仅仅在此列出上次的代码:
package com.ict.shrd;
//import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Attribute;
import java.util.List;
import java.util.Iterator;
import org.dom4j.dom.DOMDocument;
import org.dom4j.io.XMLWriter;
import java.io.*;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import java.io.*;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.*;
public class HjbhTableNameList{
private String enName="";
private String cnName="";
private HashMap map=new HashMap();
public String getEnName() {
return enName;
}
public HashMap getTableListFromXml(File f){
try{
SAXReader reader = new SAXReader();
Document doc = reader.read(f);
Element root = doc.getRootElement();
Element firstChild=root.element("hjbh");
for (Iterator i = firstChild.elementIterator("tableName"); i.hasNext();) {
Element foo = (Element) i.next();
this.enName=foo.attributeValue("enName");
this.cnName=foo.getText();
map.put(enName,cnName);
}
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
public static void main(String arge[]) {
File f = new File("E:\\jiangcm\\workspace-forict\\JavaBasis\\xml\\shrd.xml");
HashMap map=new HashMap();
HjbhTableNameList tableList=new HjbhTableNameList();
map=tableList.getTableListFromXml(f);
Set enNameSet=map.keySet();
String enName="";
for (Iterator i = enNameSet.iterator(); i.hasNext();) {
enName=(String)i.next();
//System.out.println(enName);
System.out.println(map.get(enName));
}
}
}
二。dom4j生成xml树:
完整代码:
package xml;
import org.dom4j.*;
import java.io.*;
public class XmlCreator{
public void createXML(String fileName) {
Document doc = org.dom4j.DocumentHelper.createDocument();
Element root = doc.addElement("book");
root.addAttribute("name", "我的图书");
Element childTmp;
childTmp = root.addElement("price");
childTmp.setText("21.22");
Element writer = root.addElement("author");
writer.setText("李四");
writer.addAttribute("ID", "001");
try {
//注意这里使用的是FileOutputStream,而不是FileWriter,因为涉及到编码问题
//详细见“dom4j编码问题解决”篇。
org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(
new FileOutputStream(fileName));
xmlWriter.write(doc);
xmlWriter.close();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args){
XmlCreator xmlCreator=new XmlCreator();
xmlCreator.createXML("E:\\jiangcm\\book.xml");
}
}