可以在http://dom4j.org下载,最好下载ZIP包(找不到就问我要吧),里面有除了dom4j-1.6.1.jar之外还有jaxen-1.1-beta-6.jar等包。
一个简单例子
import java.io.File;
import java.io.*;
import java.util.*;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.DocumentException;
public class test{
public void createBookInfor(String filename,String content){
Calendar rightNow = Calendar.getInstance();
Date thisTime = rightNow.getTime();
Document document = DocumentHelper.createDocument();
document.addComment("Generated by: http://www.chinascript.com/ $Revision: 1.0 $");//添加注释
Element chapterElement = document.addElement("chapter");//建立名为chapter的根节点
Element pageElement = chapterElement.addElement("page");//建立page节点
pageElement.addAttribute("id","1");//添加page的属性
Element timeElement = pageElement.addElement("time");//建立time节点
timeElement.setText(thisTime.toString());//填加当前时间
Element contentElement = pageElement.addElement("content");//建立content节点
contentElement.setText(content);//添加内容
try {
XMLWriter output = null;
/** 格式化输出,类型IE浏览一样 */
OutputFormat format = OutputFormat.createPrettyPrint();
/** 指定XML字符集编码 */
format.setEncoding("UTF-8");
output = new XMLWriter(new FileOutputStream(new File(filename)), format);
/*注意:FileOutputStream和FileWriter*/
output.write(document);
output.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
另外,在XML中增加节点:
try&nb