import java.io.File;
import java.io.FileWriter;
import org.dom4j.io.XMLWriter;
import org.dom4j.*;
public class CreateDoc{
public int createXMLFile(String filename){
/** 返回操作結(jié)果, 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節(jié)點 */
Element bookElement = booksElement.addElement("book");
/** 加入show屬性內(nèi)容 */
bookElement.addAttribute("show","yes");
/** 加入title節(jié)點 */
Element titleElement = bookElement.addElement("title");
/** 為title設(shè)置內(nèi)容 */
titleElement.setText("Dom4j Tutorials");
/** 加入author節(jié)點*/
Element authorElement = booElement.addElement("author");
/** 為author 設(shè)置CDTAT */
authorElement.addCDATA("<h1 id=\"h1title\">(.*?)</h1>");
/** 類似的完成后兩個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節(jié)點 */
Element ownerElement = booksElement.addElement("owner");
ownerElement.setText("O'Reilly");
try{
/** 將document中的內(nèi)容寫入文件中 */
XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));
writer.write(document);
writer.close();
/** 執(zhí)行成功,需返回1 */
returnValue = 1;
}catch(Exception ex){
ex.printStackTrace();
}
return returnValue;
}
public static void main(String[]args){
CreateDoc cd=new CreateDoc();
int i=cd.createXMLFile("D:\\mybook.xml");
if(i==1){
System.out.println("建立成功!");
}
else{
System.out.println("建立失敗!");
}
}
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。