以下介紹Dom4j的環境是:windowsXP、eclipse3.5.0、jdk1.6、Dom4j1.6.1.jar
Dom4j1.6.1.jar架包可以在本人的資源中下載,歡迎下載使用
xml的合併問題,確保xml的結構相同
//合併2個xml
public static void getMergerXml(String folderxmlpath,String xmlresultpath){
createDoucument_01(xmlresultpath);//創建合併後的xml
SAXReader readerxml=new SAXReader();
File[] file = new File(folderxmlpath).listFiles();//獲取所有的xml文件
try {
Document docresult=readerxml.read(new File(xmlresultpath));//將合併後的xml文件轉成document對象
Element elementresult=docresult.getRootElement();//獲取document對象的根節點
for(int i = 0;i<file.length;i++){
Document docfile = readerxml.read(file[i]);//將要合併的xml對象包裝成一個document對象
Element elementfile=docfile.getRootElement();//獲取要合併的document對象的跟節點
elementresult.add(elementfile);//給合併後的xml對象中添加要合併的對象
}
WriteInFiler(docresult,xmlresultpath);//將合併後的document對象寫入xml中
} catch (DocumentException e) {
e.printStackTrace();
}
}
//將folderxmlpath文件夾下的所有xml合併
public static void getMergerAllXml(String folderxmlpath,String xmlresultpath){
SAXReader readerxml=new SAXReader();
createDoucument_01(xmlresultpath);//創建合併後的xml
List xmlpath = recursion_Directory(new File(folderxmlpath),new ArrayList());//獲取該目錄下所有的xml文件絕對路徑
try {
Document docresult=readerxml.read(new File(xmlresultpath));//將合併後的xml文件轉成document對象
Element elementresult=docresult.getRootElement();//獲取document對象的根節點
for(int i = 0;i<xmlpath.size();i++){
Document docfile = readerxml.read(new File(xmlpath.get(i).toString()));//將要合併的xml對象包裝成一個document對象
Element elementfile=docfile.getRootElement();//獲取要合併的document對象的跟節點
elementresult.add(elementfile);//給合併後的xml對象中添加要合併的對象
}
WriteInFiler(docresult,xmlresultpath);//將合併後的document對象寫入xml中
} catch (DocumentException e) {
e.printStackTrace();
}
}
//將document對象內容寫入文件doc.xml文件中
public static void WriteInFiler(Document doc,String xmlpath){
try{
OutputFormat opt=OutputFormat.createPrettyPrint();
opt.setEncoding("GB2312");
XMLWriter w=new XMLWriter(new FileWriter(new File(xmlpath)),opt);
w.write(doc);
w.close();
}catch(Exception e){
e.printStackTrace();
}
}
//創建合併後的xml文件
public static void createDoucument_01(String xmlpath){
//創建xml文檔,並設置文檔根元素
Document document =DocumentHelper.createDocument();
Element element1 = DocumentHelper.createElement("root");
document.setRootElement(element1);//快捷鍵:ctrl+shift+o
//輸出到指定文件,設置其字符編碼和輸出格式
OutputFormat format=new OutputFormat(" ",true);
format.setEncoding("GBK");//設置xml的字符編碼格式
try{
XMLWriter xml3=new XMLWriter(new FileOutputStream(xmlpath),format);
xml3.write(document);
xml3.close();
}catch(IOException se){
se.printStackTrace();
}
}
//遞歸獲取file下的所有xml文件絕對路徑
public static List recursion_Directory(File file,List fileList){
File[] files=file.listFiles();
if(files!=null&&files.length>0){
for(File filechild : files){
if(filechild.isDirectory()){//如果是文件夾
recursion_Directory(filechild,fileList);//遞歸查詢
}else{
String filepath = filechild.getPath();
String suffix = filepath.substring(filepath.lastIndexOf("."));
if(suffix.equals(".xml")){
fileList.add(filepath);
}
}
}
}
return fileList;
}