Dom4j是一个易用的、开源的库,用于XML,XPath和XSLT解析。它应用于Java平台,采用了Java集合框架并完全支持DOM,SAX和JAXP。官方网址:http://www.dom4j.org/。
Dom4J在很多方面拥有更强大的功能,鼎鼎有名的Hibernate也使用它来做XML配置文件的解析。
import java.io.FileWriter;
import java.io.IOException;
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;
public class DOMCreator ...{
public static void main(String[] args) throws IOException, DocumentException ...{
Document table = DocumentHelper.createDocument();
Element root = table.addElement(Constants.DATA_TABLE);
Element row = root.addElement(Constants.DATA_ROW);
Element item = row.addElement(Constants.DATA_ITEM);
item.addText("data");
OutputFormat format = OutputFormat.createPrettyPrint();
FileWriter writer = new FileWriter("dom4j.xml");
XMLWriter outputter = new XMLWriter(writer, format);
outputter.write(table);
outputter.close();
SAXReader reader = new SAXReader();
Document document = reader.read("dom4j.xml");
XMLWriter domstream = new XMLWriter(System.out, format);
domstream.write(document);
domstream.close();
}
}
常量声明文件:
public interface Constants ...{
public static String DATA_TABLE = "Table";
public static String DATA_ROW = "Row";
public static String DATA_ITEM = "Item";
}
dom4j的详细介绍可参阅:http://xhy0422.javaeye.com/blog/50235
示例可参阅http://blog.csdn.net/yedian/archive/2007/12/19/1954194.aspx