天天看點

使用dom4j對xml的讀寫和修改

使用dom4j對xml的讀寫修改,首先還是需要的jar

此處使用的jar版本是dom4j-1.6.1.jar ,此外使用dom4j還需要另外一個jar就是jaxen-1.1-beta-6.jar,否則使用将報錯

下載下傳位址http://download.csdn.net/download/liu119361940/5349921

個人感覺dom4j,使用起來應該更友善點,比jdom多點東西。。

ok,下面是代碼:

package com.dom4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.ProcessingInstruction;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlWriterAndReader {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws DocumentException 
	 */
	public static void main(String[] args) throws IOException, DocumentException {
		// TODO Auto-generated method stub
//		String path = "dom4j.xml";
//		String pathEdit = "dom4jEdit.xml";
		String path = "D:/dom4j.xml";
		String pathEdit = "D:/dom4jEdit.xml";
		createXml(path);
		System.out.println("建立後直接讀取》》》》》》》》》》》》》");
		System.out.println("建立後直接讀取》》》》》》》》》》》》》");
		System.out.println("建立後直接讀取》》》》》》》》》》》》》");
		readXml(path);
		System.out.println("修改後讀取》》》》》》》》》》》》》");
		System.out.println("修改後讀取》》》》》》》》》》》》》");
		System.out.println("修改後讀取》》》》》》》》》》》》》");
		editXml(path,pathEdit);
	}

	/**
	 * 建立xml
	 * @param path
	 * @throws IOException
	 */
	public static void createXml(String path) throws IOException{
		//使用 DocumentHelper 類建立一個文檔執行個體。 DocumentHelper 是生成 XML 文檔節點的 dom4j API 工廠類       
		Document doc = DocumentHelper.createDocument();   
		Element root = DocumentHelper.createElement("root"); 
		doc.setRootElement(root);
		
		//添加節點和屬性
		for(int i=0;i<2;i++){
			Element user= root.addElement("user");
			user.addEntity("name", "jack");
			Element info= user.addElement("info");
			info.addAttribute("sex", "mail"+1);
			info.addAttribute("age", "1"+1);
			info.addEntity("a", "a");
			info.addText("bbb");
			Element other= user.addElement("other");
			other.addAttribute("address", "位址"+i);
			other.setText("");
			Element jianjie = user.addElement("jianjie");
			jianjie.addText("一個人在戰鬥");
		}		
		root.addAttribute("name", "value");
		Element fff= root.addElement("fff");
		fff.addAttribute("bbb", "ccc");
		root.addText("txt");
		
		root.addComment("comment");
		root.addCDATA("cdata");
		ProcessingInstruction pi =  DocumentHelper.createProcessingInstruction("xml-stylesheet",
			      "href=\"bookList.html.xsl\" type=\"text/xsl\"");
		root.add(pi);
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlout = new XMLWriter(new FileOutputStream(path),format);
		xmlout.write(doc);
		xmlout.close();
	}
	
	
	/**
	 * 讀取xml
	 * @param path
	 * @throws DocumentException
	 */
	public static void readXml(String path) throws DocumentException{
		//使用 SAXReader 解析 XML 文檔 catalog.xml       
        SAXReader saxReader = new SAXReader();       
        Document doc = saxReader.read(new File(path));  
        
		Element root = doc.getRootElement();
		repeat(root);
	}
	
	/**
	 * 修改xml
	 * @param path
	 * @param editPath
	 * @throws DocumentException
	 * @throws IOException
	 */
	public static void editXml(String path,String editPath) throws DocumentException, IOException{
		//使用 SAXReader 解析 XML 文檔 dom4j.xml       
        SAXReader saxReader = new SAXReader();       
        Document doc = saxReader.read(new File(path));  
        
		Element root = doc.getRootElement();
		
//		List<Element> user = root.selectNodes("//root/@user");
		List<Element> users = root.selectNodes("user");
		Iterator<Element> it = users.iterator();
		while(it.hasNext()){	//對節點添加内容
			Element u =  it.next();
			u.addAttribute("name2", "新加的名稱2");
			u.setText(u.getTextTrim()+"text也加啦");
		}
		
		List<Element> infos = doc.selectNodes("//user/info");
		Iterator<Element> iit = infos.iterator();
		while(iit.hasNext()){	//修改節點内容
			Element info =  iit.next();
			info.attribute("sex").setText(info.attribute("sex").getText()+"-value");
			info.attribute(1).setValue(info.attribute(1).getValue()+"-value");
		}
		
		List<Element> jianjies = doc.selectNodes("//jianjie");
		Iterator<Element> iiit = jianjies.iterator();
		while(iiit.hasNext()){
			Element jianjie =  iiit.next();
			jianjie.setText(jianjie.getTextTrim()+"-到兩個人的奮鬥");
		}
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlout = new XMLWriter(new FileOutputStream(editPath),format);
		xmlout.write(doc);
		xmlout.close();
		
		//重新讀取xml
		Document doc2 = saxReader.read(new File(editPath));
		Element root2 = doc2.getRootElement();
		repeat(root2);
	}

	
	/**
	 * 遞歸取出xml中的值方法1 
	 */
	public static void  repeat(Element ele){
		if(checkChild(ele)){
			System.out.println("Element: " + ele.getName());
			List<Attribute> attr = ele.attributes();
	    	for(int n=0;n<attr.size();n++){
	    		System.out.println("Attribute: " + (attr.get(n)).getName()+"=="+(attr.get(n)).getValue());
	    		System.out.println("Text1: " + ele.getTextTrim());		    		
	    	}
	    	List<Element> list = ele.elements();
	    	Iterator it = list.iterator();
	    	while (it.hasNext()) {
	    		Element element = (Element) it.next();
	    		repeat(element);
	    	}
		}else{
			System.out.println("Element: " + ele.getName());
   	    	System.out.println("Text2: " + ele.getTextTrim());
   	    	List<Attribute> attr = ele.attributes();
	    	for(int n=0;n<attr.size();n++){
	    		System.out.println("Attribute: " + (attr.get(n)).getName()+"=="+(attr.get(n)).getValue());
	    	}
		}
	}
	
	/**
	 * 檢測節點是否還有子節點
	 * @param element
	 * @return
	 */
	public static boolean checkChild(Element element){
		if(!(element.elements()).isEmpty()){
			return true;
		}else{
			return false;
		}
	}
}