實例:
holen.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<!--This is a test for dom4j, holen, 2004.9.11-->
<book show="yes">
<title>Dom4j Tutorials</title>
</book>
<book show="yes">
<title>Lucene Studing</title>
</book>
<book show="no">
<title>Lucene in Action</title>
</book>
<owner>O'Reilly</owner>
</books>
建立一個XML文檔:
/**
* 建立一個XML文檔,文檔名由輸入屬性決定
* @param filename 需建立的文件名
* @return 返回操作結果, 0表失敗, 1表成功
*/
public int createXMLFile(String filename){
/** 返回操作結果, 0表失敗, 1表成功 */
int returnValue = 0;
/** 建立document對象 */
Document document = DocumentHelper.createDocument();
/** 建立XML文檔的根books */
Element booksElement = document.addElement("books");
/** 加入一行注釋 */
booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");
/** 加入第一個book節點 */
Element bookElement = booksElement.addElement("book");
/** 加入show屬性內容 */
bookElement.addAttribute("show","yes");
/** 加入title節點 */
Element titleElement = bookElement.addElement("title");
/** 為title設置內容 */
titleElement.setText("Dom4j Tutorials");
/** 類似的完成後兩個book */
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","yes");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene Studing");
bookElement = booksElement.addElement("book");
bookElement.addAttribute("show","no");
titleElement = bookElement.addElement("title");
titleElement.setText("Lucene in Action");
/** 加入owner節點 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try{
/** 將document中的內容寫入文件中 */
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
/** 執行成功,需返回1 */
returnValue = 1;
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
說明:
Document document = DocumentHelper.createDocument();
通過這句定義一個XML文檔對象。
Element booksElement = document.addElement("books");
通過這句定義一個XML元素,這里添加的是根節點。
Element有幾個重要的方法:
l addComment:添加註釋
l addAttribute:添加屬性
l addElement:添加子元素