1. 程式人生 > >DOM4J 和xpath的簡單實用

DOM4J 和xpath的簡單實用

Dom4j是一個簡單靈活的開放原始碼的庫,Dom4j是由早期開發Jdom的人分離出來獨立開發的,與jdom不同的是,dom4j使用介面和抽象型別,雖然dom4japi相對要複雜一些,但是它提供了比jdom更好的靈活性。

Dom4j是一個非常優秀的java xml api ,具有效能優異,功能強大和極易使用的特點,現在很多軟體採用的DOM4J例如Hibernate,包括sun公司自己的jaxm也使用了DOM4J.

使用DOM4J開發需要下載想用的dom4j響應的jar檔案。dom4j-1.6.1.jar

dom4j的api文件描寫的比較詳細:

實用dom4j對book.xml進行增刪改查

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE 書架>

<書架> 
  <書> 
    <書名 name="xxx">鋼鐵是怎樣煉成的</書名>  
    <作者>尼·奧斯特洛夫斯基</作者>  
    <售價>16.5</售價>   
  </書>  
  <書> 
    <書名 name="yyy">假如給我三天光明</書名>  
    <作者>aobama</作者>  
    <售價>17.6</售價> 
  </書> 
</書架>

 

package cn.dom4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.junit.Test;

public class Demo1 {
	
	//讀物ml文件第二本書名的值
	@Test
	public void read() throws DocumentException{
		SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        Element root = document.getRootElement();
        Element book = (Element) root.elements("書").get(1);
        String name = book.element("書名").getText();
        System.out.println(name);
	}
	
	//讀物ml文件第二本書名的屬性
		@Test
		public void read1() throws DocumentException{
			SAXReader reader = new SAXReader();
	        Document document = reader.read(new File("src/book.xml"));
	        Element root = document.getRootElement();
	        Element book = (Element) root.elements("書").get(1);
	        String value= book.element("書名").attributeValue("name");
	        System.out.println(value);
		}
		//在第一本書新增售價209
		@Test
		public void add() throws DocumentException, IOException{
			SAXReader reader = new SAXReader();
	        Document document = reader.read(new File("src/book.xml"));
	        Element book = document.getRootElement().element("書");
			book.addElement("售價").setText("209元");
			
			 //FileWriter fileWiter = new FileWriter("src/book.xml");  會出現亂碼
			 OutputStreamWriter fileWiter = new OutputStreamWriter(new FileOutputStream("src/book.xml"),"utf-8");
		     XMLWriter writer = new XMLWriter(fileWiter);
		     writer.write( document );
		     writer.close();
		     
		     
		     //或者    FileWrite檢視的預設是gb2312表  
		     OutputFormat format = OutputFormat.createPrettyPrint();
		     format.setEncoding("UTF-8");
		     XMLWriter writer2 = new XMLWriter(new FileOutputStream("src/book.xml"),format);
		     writer2.write(document);
		     writer2.close();
		}
		
		//在第一本書指定位置新增售價209  更改了list集合的順序
		@Test
		public void add2() throws DocumentException, IOException{
			SAXReader reader = new SAXReader();
	        Document document = reader.read(new File("src/book.xml"));
	        Element book = document.getRootElement().element("書");
			List list = book.elements(); //書名售價  
			Element price = DocumentHelper.createElement("售價");
			price.setText("309元");
			list.add(2,price);
			
			 OutputFormat format = OutputFormat.createPrettyPrint();
		     format.setEncoding("UTF-8");
		     XMLWriter writer2 = new XMLWriter(new FileOutputStream("src/book.xml"),format);
		     writer2.write(document);
		     writer2.close();
			
		}
		
		//刪除新增的售價節點;
		@Test
		public void delete() throws DocumentException, IOException{
			SAXReader reader = new SAXReader();
	        Document document = reader.read(new File("src/book.xml"));
			
			Element price = document.getRootElement().element("書").element("售價");
			price.getParent().remove(price);
			
			OutputFormat format = OutputFormat.createPrettyPrint();
		     format.setEncoding("UTF-8");
		     XMLWriter writer2 = new XMLWriter(new FileOutputStream("src/book.xml"),format);
		     writer2.write(document);
		     writer2.close();
		}
		
		@Test
		public void update() throws Exception{
			SAXReader reader = new SAXReader();
	        Document document = reader.read(new File("src/book.xml"));
			
			Element book = (Element) document.getRootElement().elements("書").get(1);
			book.element("作者").setText("aobama");
			OutputFormat format = OutputFormat.createPrettyPrint();
		     format.setEncoding("UTF-8");
		     XMLWriter writer2 = new XMLWriter(new FileOutputStream("src/book.xml"),format);
		     writer2.write(document);
		     writer2.close();
		}
		
}

簡單實用xpath來實現驗證使用者密碼。xpath的語法比較簡單,可查閱xpath Tutorial

users.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
	<user id="1" username="aaa" password="123" email="[email protected]"></user>
	<user id="2" username="bbb" password="123" email="[email protected]"></user>
	<user id="3" username="ccc" password="123" email="[email protected]"></user>
	<user id="4" username="ddd" password="123" email="[email protected]"></user>


</users>
package cn.dom4j;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;


/*使用xpath提取文件資料
 * 
 * 
 * */
public class Demo2 {
	public static void main(String[] args) throws DocumentException {
		/*SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        
        String value  = document.selectSingleNode( "//作者" ).getText();
        
        System.out.println(value);
        
        List list = document.selectNodes("//作者");
        for (int i=0;i<list.size();i++){
        	Element e =(Element) list.get(i);
        	System.out.println(e.getText());
        }*/
		
		String username="aaa";
		String password="123";
		SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/users.xml"));
        
        //user[@username='vvv' and @password='123']
        Node node = document.selectSingleNode("//user[@username='" + username+"' and @password='"+ password+"']");
        if (node==null){
        	System.out.println("使用者名稱或者密碼錯誤");
        }else{
        	System.out.println("登入成功");
        }
        
        
	}
}