1. 程式人生 > >dom4j 遍歷所有元素和屬性

dom4j 遍歷所有元素和屬性

 Dom4j是java中常用讀取xml檔案的工具,就方便性和效能方面,一定程度要優於JDK中Domcument和SAX解析的。
package Test;
import org.dom4j.Attribute;
import org.dom4j.Document; 
import org.dom4j.DocumentException; 
import org.dom4j.Element; 
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.*; 
public class XmlTest { 

    public static void main(String args[]) throws DocumentException { 
        XmlTest test = new XmlTest(); 
        
        Element element;
		try {
			element = test.testGetRoot("d:\\MS01003 藥品目錄 V2.00.xml");
	        String x= element.asXML();
			String newfileName = "d:\\MS01003 藥品目錄 V2.00"+"-新.xml";
			writeFile(newfileName, formatXml(x, "utf-8", false), "utf-8");
	        
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    } 

    public Element testGetRoot(String pathName) throws Exception{  
        SAXReader sax=new SAXReader();//建立一個SAXReader物件  
        File xmlFile=new File(pathName);//根據指定的路徑建立file物件  
        Document  document=sax.read(xmlFile);//獲取document物件,如果文件無節點,則會丟擲Exception提前結束  
        Element root=document.getRootElement();//獲取根節點  
        this.getNodes(root);//從根節點開始遍歷所有節點  
        return root;
    }  
    
    /** 
     * 遞迴遍歷方法 
     * 
     * @param element 
     */ 

	public void getNodes(Element node){  
	    
	  //當前節點的名稱、文字內容和屬性  
	  node.setText("");
	  List<Attribute> listAttr=node.attributes();//當前節點的所有屬性的list  
	  for(Attribute attr:listAttr){//遍歷當前節點的所有屬性  
	      attr.setText("");
	  }  
	  //遞迴遍歷當前節點所有的子節點  
	  List<Element> listElement=node.elements();//所有一級子節點的list  
	  for(Element e:listElement){//遍歷所有一級子節點  
	      this.getNodes(e);//遞迴  
	  }  
	}  
	
	
	public static Document getTempletdoc(String templetName){
		SAXReader reader = new SAXReader();
		Document templetdoc = null;
		try {
			 templetdoc = reader.read(new File(templetName));
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return templetdoc;
	}
	
	
	 public static String formatXml(String content, String charset, boolean istrans) { 
         OutputFormat format = OutputFormat.createPrettyPrint(); 
         format.setEncoding(charset); 
         StringWriter sw = new StringWriter(); 
         XMLWriter xw = new XMLWriter(sw, format); 
         xw.setEscapeText(istrans); //istrans false這樣&符號就不會被轉義了
         try { 
                 xw.write(content); 
                 xw.flush(); 
                 xw.close(); 
         } catch (IOException e) { 
                 System.out.println("格式化XML文件發生異常,請檢查!"); 
                 e.printStackTrace(); 
         } 
         return sw.toString(); 
	 } 
	 
	 public static  void writeFile(String filePathAndName, String fileContent,String charsetName) {   
		    try {   
		        File f = new File(filePathAndName);   
		        if (!f.exists()) {   
		            f.createNewFile();   
		        }   
		        OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),charsetName);   
		        BufferedWriter writer=new BufferedWriter(write);     
		        writer.write(fileContent);   
		        writer.close();   
		    } catch (Exception e) {   
		        System.out.println("寫檔案內容操作出錯");   
		        e.printStackTrace();   
		    }   
		}   
}

jar包免費下載