DOM4J creates a tree object model in memory for an XML document. It provides a powerful set of Easy-to-use APIs that process, manipulate, or traverse XML files through XPath and XSLT, as well as the integration of Sax, JAXP, and Dom.
To provide a highly configurable implementation strategy, DOM4J is based on interface design. Just provide a documentfactory implementation, and you can create your own XML tree implementation. This design makes it very easy to reuse dom4j code when extending dom4j to customize the features you need.
This document will provide you with a dom4j practice guide in the form of code instances. In the lab project, this open source toolkit has brought a lot of convenience to my work, and in this article I will summarize the tasks that are used in the project to dom4j, with a view to complementing the many documents on the Internet.
reading XML files
Reading XML files in general will be very easy to manipulate in dom4j.
public void readXMLSimple(File file) throws DocumentException{
//使用SAXReader读取XML文件
SAXReader sr = new SAXReader();
Document doc = sr.read(file);
//使用XPath遍历一个XML文件的结点
Element root = doc.getRootElement();
List entryList1 = root.selectNodes("entry");
//或者
List entryList2 = doc.selectNodes("/feed/entry");
}
Create an XML document and record it on disk
Create an XML file and write it to disk. It can also be done using very brief code, assuming that we insert the list of entry nodes from the previous code example into a new XML document and then save it on disk in a graceful indentation format that we can encode as follows:
public void createXMLSimple(List entries, File f)
throws FileNotFoundException,
UnsupportedEncodingException,
IOException{
Document doc = DocumentHelper.createDocument();
doc.addElement("feed");
Element root = doc.getRootElement();
Iterator i = entries.iterator();
while(i.hasNext()){
//从别的Dom中得到的Element都有其本身
//的root,所以必须创建副本才能插入另一个doc内
root.add(((Element)i.next()).createCopy());
}
FileOutputStream os = new FileOutputStream(f);
OutputFormat of = OutputFormat.createPrettyPrint();
XMLWriter xmlw = new XMLWriter(os,of);
xmlw.write(doc);
}