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 listAttr=node.attributes();//当前节点的所有属性的list  
	  for(Attribute attr:listAttr){//遍历当前节点的所有属性  
	      attr.setText("");
	  }  
	  //递归遍历当前节点所有的子节点  
	  List 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包免费下载

dom4j-1.6.1.jar


你可能感兴趣的:(java)