XML-mfy

定義:
可擴展標記語言,一種用於標記電子文檔使其具有結果性的標記語言,它可以用來標記數據、定義數據類型,是一種允許用戶對自己的標記語言進行定義的源語言。

xml和超文本標記語言區別:
html不一定需要成對出現,xml則一定需要成對出現; html 不區分大小寫,但是xml區分。

格式良好的xml:
a)聲明信息,用於描述xml的版本和編碼方式。
<?xml version= "1.0" encoding= "UTF-8"?>p
b) xml 有且僅有-一個根元素。
c) xml 是大小寫敏感的。
d)標籤是成對的,而且要正確嵌套I
e)屬性值要使用雙引號。
f)註釋的寫法:

<?xml version="1.0" encoding="UTF-8"?>
<class>
  <className className="java.lang.Sting">
    <methodName>length</methodName>
  </className>
</class>

DTD簡介
(1)DTD,Document Type Definition,文檔類型定義.
(2)DTD用於約束xml的文檔格式,保證xml是一個有效的xml.
(3)DTD可以分爲兩種,內部DTD,外部DTD.

使用內部DTD
(1)內部DTD的定義,語法如下:

(2)元素聲明語法:
<!ELEMENT 元素名 (子元素[, 子元素...])>
(3)數量詞
   >+:表示出現1次或多次,至少一次
   >?:表示出現0次或1次
   >*:表示出現任意次
(4)屬性聲明語法:
   >屬性類型:CDATA,表示字符數據(character data)
   >默認值:
     - #REQUIRED ,表示必須出現
     - #IMPLIED,表示不是必須的

<!ATTLIST 元素名稱 屬性名稱 屬性類型 默認值>

(5)帶DTD的完整xml代碼:

<?xml version="1.0" econding="UTF-8"?>
<!-- 聲明內部DTD -->
<!DOCTYPE scores [
    <!ELEMENT scores (student+)>
    <!ELEMENT student (name,course,score)>
    <!ATTLIST student id CDATA #REQUIRED>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT course (#PCDATA)>
    <!ELEMENT score (#PCDATA)>
]>
<scores>
    <student id="1">
        <name>張三</name>
        <course>java</course>
        <score>89</score>
    </student>
    <student id="2">
        <name>李四</name>
        <course>sql</course>
        <score>69</score>
    </student>
</scores>

使用外部DTD
(1)創建一個獨立的DTD文件:scores.dtd

<?xml version="1.0" econding="UTF-8"?>
 <!ELEMENT scores (student+)>
 <!ELEMENT student (name,course,score)>
 <!ATTLIST student id CDATA #REQUIRED>
 <!ELEMENT name (#PCDATA)>
 <!ELEMENT course (#PCDATA)>
 <!ELEMENT score (#PCDATA)>

(2)在xml中引入外部DTD文件

<!-- 引入外部DTD文件 -->
<!DOCTYPE scores SYSTEM "scores.dtd">

利用Java代碼解析XML文檔
使用 dom4j工具,讀取、操作xml文件

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
 * 使用 dom4j工具,讀取、操作xml文件
 * 需要提前將工具jar包,添加到build path中
 */
public class ReadXMLDemo {
	public static void main(String[] args) throws DocumentException {
		//創建解析工具對象 org.dom4j.io.SAXReader
		SAXReader reader = new SAXReader();
		//讀取emps.xml文件,解析生成樹狀結構的文檔Document對象
		//	即,document對象中,包含了emps.xml文件中所有的內容
		Document document=reader.read(new File("Emps.xml"));
		
		System.out.println(document);
		//org.dom4j.tree.DefaultDocument@7229724f
		//[Document: name file:///D:/eclipse/workspace/xml/Emps.xml]
		
		//獲得根元素
		Element rootEle = document.getRootElement();
		System.out.println("根元素:" + rootEle);
		//根元素:org.dom4j.tree.DefaultElement@4c873330 
		//[Element: <empList attributes: []/>]
		
		//獲得子元素
		List<Element> list = rootEle.elements();
		for(Element ele:list) {
		System.out.println("子元素:" + ele);
		}
		//子元素:org.dom4j.tree.DefaultElement@41629346 [Element: <emp attributes: [org.dom4j.tree.DefaultAttribute@404b9385 [Attribute: name id value "2"]]/>]
		//子元素:org.dom4j.tree.DefaultElement@6d311334 [Element: <emp attributes: [org.dom4j.tree.DefaultAttribute@682a0b20 [Attribute: name id value "3"]]/>]
		//	子元素:org.dom4j.tree.DefaultElement@3d075dc0 [Element: <emp attributes: [org.dom4j.tree.DefaultAttribute@214c265e [Attribute: name id value "4"]]/>]
	}
}

遍歷訪問元素的屬性、子元素、元素名

import java.io.File;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class ReadXMLDemo02 {
	public static void main(String[] args) throws DocumentException {
		
		SAXReader reader = new SAXReader();
		Document document = reader.read(new File("emps.xml"));
		Element rootEle = document.getRootElement();
		
		//獲得所有的<emp>元素
		List<Element> list = rootEle.elements();
		//逐一遍歷:<emp id = "1"><name>
		for(Element ele : list) {
			System.out.println("元素名:" + ele.getName());
			
			Attribute attr = ele.attribute("id");
			System.out.print(" 屬性名: " + attr.getName());
			System.out.println(" 屬性值:" + attr.getValue());
			
			Element nameEle = ele.element("name");	//獲得指定名字的子元素
				//獲得了:<name>張三</name>
			System.out.print(" 子元素名:" + nameEle.getName());
			System.out.println("子元素文本內容:" + nameEle.getText());	
			
			Element ageEle = ele.element("age");	//獲得指定名字的子元素
			//獲得了:<name>張三</name>
			System.out.print(" 子元素名:" + ageEle.getName());
			System.out.println("子元素文本內容:" + ageEle.getText());
		
			Element genderEle = ele.element("gender");	//獲得指定名字的子元素
			//獲得了:<name>張三</name>
			System.out.print(" 子元素名:" + genderEle.getName());
			System.out.println("子元素文本內容:" + genderEle.getText());
			
			Element salaryEle = ele.element("salary");	//獲得指定名字的子元素
			//獲得了:<name>張三</name>
			System.out.print(" 子元素名:" + salaryEle.getName());
			System.out.println("子元素文本內容:" + salaryEle.getText());
		}
	}
}

使用dom4j工具,寫出一個新的xml文檔
步驟:
1)創建一個空的Document文檔對象(樹狀結構的)
2)添加一個根元素
3)向根元素中,添加子元素
4)合理地組織好樹狀結構
5)將Document對完,通過XMLWriter工具寫出

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class WriteXMLDemo {
	public static void main(String[] args) throws IOException {
		List<Emp> list = new ArrayList<Emp>();
		list.add(new Emp(1,"小李", 12, "女", 12000));
		list.add(new Emp(2,"小孟", 13, "女", 13000));
		list.add(new Emp(3,"小張", 14, "男", 14000));
		list.add(new Emp(4,"小楊", 15, "男", 15000));
		
		//1)創建一個空的Document文檔對象(樹狀結構的)
		Document document = DocumentHelper.createDocument();
		//2)添加一個根元素
		Element rootEle = document.addElement("empList");
			//注意,向document對象中添加元素的工作,只能做一次!根元素就一個!
				//document對象中的信息:
				//<?xml version="1.0" encoding="UTF-8"?>
				//<empList/>
		//向根元素中,添加<emp>元素,將返回這個元素對象
		//3)向根元素中,添加子元素
		for(Emp emp : list) {
		//	emp = new Emp();
			Element empEle = rootEle.addElement("emp");//傳入子元素的標籤名
			//向<emp>元素中,添加員工成員變量信息的子元素
			empEle.addAttribute("id", emp.getId() + "");
			Element nameEle = empEle.addElement("name");
			nameEle.addText(emp.getName());
			//使用鏈式寫法,添加子元素及文本內容
			empEle.addElement("age").addText(emp.getAge() + "");
			empEle.addElement("gender").addText(emp.getGender());
			empEle.addElement("salary").addText(emp.getSalary() + "");//傳入格式化工具
		}
		
		//4)合理地組織好樹狀結構
		System.out.println("document對象中的信息:");
		System.out.println(document.asXML());
		
		//5)將Document對完,通過XMLWriter工具寫出
		FileOutputStream fos = new FileOutputStream("emps-new.xml");
		OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
		OutputFormat format = OutputFormat.createPrettyPrint();
								//創建一個美觀的格式化工具
		XMLWriter xmlWriter = new XMLWriter(osw, format);//傳入格式化工具
		xmlWriter.write(document);//寫出xml文檔
		xmlWriter.close();
	}
}

xpath檢索

import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XPathDemo {
	public static void main(String[] args) throws DocumentException {
		//1.將xml文檔讀入,轉換爲Document文檔對象
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new File("books.xml"));
		
		//手工檢索,需要寫大量代碼
		//Element rootEle = document.getRootElement();
		//Element ele = rootEle.elementByID("1");//null
		//System.out.println(ele);
		
		//2.使用XPath工具檢索內容
		String xpath = "//book[@id='1']";//獲得id爲1的book元素
		
		//絕對路徑形式檢索
		xpath = "/bookstore/book";
				//以絕對路徑的形式,查找所有元素;<bookstore>元素下所有的<book>元素
		xpath = "/bookstore/book/title";//獲得四個<title>元素
		xpath = "/bookstore/book/*";//獲得每個<book>元素中所有的內容
		
		//沒有/時,表示在當前節點上選擇檢索
		xpath = "book";//沒有匹配的元素,集合是空的;當前節點中沒有book元素
		xpath = ".";	//表示選取當前節點
					//測試的代碼document.selectNodes("."),因此當前節點是document
		xpath = "bookstore";		//可以獲得<bookstore>節點元素
		
		//從當前節點中檢索所有匹配的元素,且不考慮位置
		xpath = "//book";//查找到所有<book>元素節點
		xpath = "//title";//查找到所有<title>元素節點
		
		//
		xpath = "//@lang";//獲得所有的語種
		xpath = "//@category";//獲得所有的類別
		
		//使用謂語,添加篩選條件
		xpath = "//book[1]";//獲取符合檢索條件的第一個元素
		xpath = "//book[last()]";//使用last()函數,定位到最後一個元素
		xpath = "//book[last()-1]";//使用last()-1函數,定位到倒數第二個個元素
		xpath = "//book[position()<3]";//獲得前兩個元素,下標從1開始計數
		
		//使用謂語,結合元素的屬性,增加篩選條件
		xpath = "//book[@id]";		//查找所有的書,並且帶有id屬性
		xpath = "//book[@id='2']";		//查找id爲2的書
		
		//使用謂語,結合元素的子元素,增加篩選條件
		xpath = "//book[price>35]";//查找價格大於35元的書
		xpath = "//book[price>35]/title";//查找價格大於35元的書 的標題
		
		xpath = "//title[@*]";//查找出帶有屬性的<title>
		
		System.out.println("使用" + xpath + "進行xpath檢索,得到的結果是:");
		List list = document.selectNodes(xpath);
		for(Object obj : list) {
			System.out.println("獲得的節點是:");
			System.out.println(obj);
			
			System.out.println("XML形式:");
			Element ele = (Element)obj;
			System.out.println(ele.asXML());
		}
		//org.dom4j.tree.DefaultElement@6bf2d08e [Element: 
		//<book attributes: [org.dom4j.tree.DefaultAttribute
		//@48cf768c [Attribute: name category value "COOKING"]]/>
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章