經常使用框架(Dom4j)

經常使用框架(Dom4j)html

一、XMLjava

基本的定義編程

xml是一種標記語言
//標準的html,html是xml的一個子集
<html>
  <head><title>標題</title></head>
  <body>
  </body>
</html>

//標準的xml,xml能夠任意定義元素
<books>
  <book>
    <id></id>
    <title></title>
    <author></author>
  </book>
</books>

//不合法的xml,xml不能出現循環嵌套
<id>
  <head>
</id>
  </head>

//也是不合法的,xml必須有結束
<id><head></id>

//合法的,節點能夠自結束
<id>
  <head/>
</id>

<book id="1">  //id表示的是book的屬性(Attribute)--book是一個節點(Node|Element)
  <title>java編程思想</title>  //title也是一個Node,java編程思想 也是一個Node(文本節點)
</book>

使用XML能夠有效的實現對象到字符串的轉換網絡

public class Book {
	private int id;
	private String title;
	private String author;
	private double price;


Book b = new Book();
b.setId(Integer.parseInt(ele.attributeValue("id")));
b.setTitle(ele.elementText("title"));
b.setAuthor(ele.elementText("author"));
b.setPrice(Double.parseDouble(ele.elementText("price")));


<book id="1">
   <title>Java編程思想</title>
   <author>Bruce Eckel</author>
   <price>69.00</price>
</book>

基於Java處理XML框架

dom4j-->不是j2se所自帶的,須要經過網絡下載這個文件包才能使用。dom

dom4j的安裝函數

一、下載dom4j工具

對於全部的基於java的第三方工具,下載的地點只有一個選擇:官方網站。學習

下載的選擇:版本選擇測試

xxx-1.6.0-SNAPSHOT.jar(快照版本,內部都沒有通過測試的版本)

xxx-alpha.jar(表示的alpha版本,這種版本表示內部測試版)

xxx-beta.jar(內部測試已經完成,外部測試版本)

以上版本能夠在學習的時候使用,可是絕對不能用於正式的項目。

xxx-release.jar(已經發布的版本)

xxx-GA.jar(徹底穩定版本)

release和GA的版本是能夠直接使用的版本。

二、將jar包添加到環境變量

經常使用的方式

一、在項目中建立一個Folder(建議的名稱就是lib)

二、將dom4j中的lib中的文件和dom4j.jar拷貝到這個lib中

三、將這些文件添加到buildpath中

若是出現如下就表示添加成功

三、寫一個類測試dom4j

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

public class Test01 {
	public static void main(String[] args) {
		try {
			SAXReader reader = new SAXReader();
			Document d = reader.read(new File("d:/test/test.xml"));
			System.out.println(d);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}

這一步不是必須的,可是建議引入

一、按住ctrl點擊某個類

二、點擊Attach Source

基於Dom4j的操做

獲取類路徑下的文件

File f = new File("books.xml");
		//由於在不一樣的包中,因此沒法找到
		System.out.println(f.exists());
		/*
		 * 要獲取類路徑下的文件能夠經過類.class.getResource("文件名")
		 */
		URL url = Test02.class.getResource("books.xml");
		//根據url獲取完整的路徑
		System.out.println(url.getPath());
		f = new File(url.getPath());
		System.out.println(f.exists());

對於XML文檔的基本訪問

try {
			SAXReader reader = new SAXReader();
			//獲取xml包中的books.xml
			Document d = reader.read(TestXML03.class
					.getResourceAsStream("xml/books.xml"));
			//獲取根元素
			Element re = d.getRootElement();
			System.out.println("root:"+re.getName());
			//並非null,而是一組空字符串
			System.out.println(re.elementText("book"));
			//獲取root的全部子節點
			List<Element> eles = re.elements();
			for(Element ele:eles) {
				//System.out.println(ele.getName());
				//獲取屬性爲id的值
				System.out.println(ele.attributeValue("id"));
				//獲取某個特定子節點中的元素的文本值
				System.out.println(ele.elementText("title")+":"+ele.elementText("price"));
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}

基於XPath的訪問

SAXReader reader = new SAXReader();
			Document d = reader.read(TestXPath.class.getResource("xml/books.xml"));
			Element root = d.getRootElement();
			/**
			 * 相對路徑查找,從當前節點查找子節點book
			 */
			List<Element> eles = root.selectNodes("book");
			System.out.println(eles);
			/**
			 * 使用絕對路徑來查找,從根books節點查找book節點(此時不會去查找book下的子節點)
			 */
			eles = root.selectNodes("/books/book");
			System.out.println(eles.size()+":"+eles);
			/**
			 * 根節點不是book,因此沒法查找
			 */
			eles = root.selectNodes("/book");
			System.out.println(eles.size()+":"+eles);
			/**
			 * 表示從文檔中遍歷全部知足要求的節點(從根節點開始)
			 * 不太建議使用,由於效率不高
			 */
			eles = root.selectNodes("//title");
			System.out.println(eles.size()+":"+eles);
			/**
			 * 查找了全部做者爲Bruce Eckel的書
			 */
			//author:節點下的元素節點
			eles = root.selectNodes("/books/book[author='Bruce Eckel']");
			for(Element e:eles) {
				System.out.println(e.elementText("title"));
			}
			System.out.println("--------------------------------------------");
			/**
			 * 查找了屬性中id大於等於2的書
			 */
			//使用@能夠遍歷屬性節點的值
			eles = root.selectNodes("/books/book[@id>=2]");
			for(Element e:eles) {
				System.out.println(e.elementText("title"));
			}
			/**
			 * 查找名稱中包含有java的price節點
			 */
			// /price獲得的是price節點而不是book節點
			//contains(title,'java'):xpath的函數,第一個參數不加引號
			//由於是xml中的節點名稱,第二個加引號表示是一個比較的字符串
			eles = root.selectNodes("/books/book[contains(title,'java')]/price");
			for(Element e:eles) {
				System.out.println(e.getTextTrim());
			}
			System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
			/**
			 * 查找名稱中包含有java而且價格小於50的書
			 */
			eles = root.selectNodes("/books/book[contains(title,'java') and price<50]");
			for(Element e:eles) {
				System.out.println(e.elementText("title")+":"+e.elementText("price"));
			}

向xml中寫數據

一、建立Document

//寫數據首先要建立一個document對象
			Document d = DocumentHelper.createDocument();

二、添加元素

//爲d添加節點,而且返回該節點
			Element root = d.addElement("users");
			//爲根節點添加節點,而且返回添加的節點
			Element eu = root.addElement("user");
			//添加屬性
			eu.addAttribute("id", "1");
			//添加username和password兩個節點
			eu.addElement("username").addText("張三");
			eu.addElement("password").addText("123456");
			eu = root.addElement("user");
			eu.addAttribute("id", "2");
			eu.addElement("username").addText("李四");
			eu.addElement("password").addText("2222222");

三、建立XMLWriter

//獲取xml文件所在的路徑
			String path = TestWrite2XML.class.getResource("xml/users.xml").getPath();
			//在學習時可使用這種方法
			//會默認修改bin下的文件,將路徑從bin替換成src
			path = path.replace("bin", "src");
			//建立XMLWriter來寫數據
			out = new XMLWriter(new FileWriter(path),OutputFormat.createPrettyPrint());

四、經過XMLWriter寫數據

//將節點寫到xml文檔中
			out.write(d);

完整代碼

XMLWriter out = null;
		try {
			//寫數據首先要建立一個document對象
			Document d = DocumentHelper.createDocument();
			//爲d添加節點,而且返回該節點
			Element root = d.addElement("users");
			//爲根節點添加節點,而且返回添加的節點
			Element eu = root.addElement("user");
			//添加屬性
			eu.addAttribute("id", "1");
			//添加username和password兩個節點
			eu.addElement("username").addText("張三");
			eu.addElement("password").addText("123456");
			eu = root.addElement("user");
			eu.addAttribute("id", "2");
			eu.addElement("username").addText("李四");
			eu.addElement("password").addText("2222222");
			//獲取xml文件所在的路徑
			String path = TestWrite2XML.class.getResource("xml/users.xml").getPath();
			//在學習時可使用這種方法
			//會默認修改bin下的文件,將路徑從bin替換成src
			path = path.replace("bin", "src");
			//建立XMLWriter來寫數據
			out = new XMLWriter(new FileWriter(path),OutputFormat.createPrettyPrint());
			//將節點寫到xml文檔中
			out.write(d);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			//須要關閉XMLWriter
			try {
				if(out!=null) out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
相關文章
相關標籤/搜索