JAVA使用SAX技術讀取XML文檔

在讀取XML文檔之前先要寫好一個xml文檔,示例xml文檔如下

innerdtd.xml

<?xml version="1.0" encoding="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>www</name>
        <course>java</course>
        <score>66</score>
    </student>
    <student id="2">
        <name>eee</name>
        <course>php</course>
        <score>77</score>
    </student>
</scores>

這個xml文檔格式良好,一個根元素,兩個子元素。

xml解讀技術主要由DOM技術、SAX技術、JDOM技術、DOM4J技術,此次示例運用的是SAX。其他的技術寫法與此相似,導入的jar包會不同而已。

  1. 首先,在eclipse中new一個class,名爲TestXml.java

  2. 其次,下載導入jar包,dom4j.jar
    官方下載地址如下:https://dom4j.github.io/
    在這裏插入圖片描述

    本人用的是dom4j-1.6.1.jar這個包。

    1. 接下來編寫程序,內容如下:
import java.io.File;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class TestXml {
	public static void main(String[] args) throws Exception{
		//1. 創建SAXReader對象,用於讀取xml文件
		SAXReader reader = new SAXReader();
		//讀取xml文件,得到document對象
		Document doc = reader.read(new File("src/innerdtd.xml"));
		//獲取根元素
		Element root = doc.getRootElement();
//		System.out.println(root.getName());
		//獲取根元素下的所有子元素
		Iterator<Element> it = root.elementIterator();
//報黃或寫爲 : Iterator<?> it = root.elementIterator();
		while(it.hasNext()){
			//取出元素
			Element e = (Element)it.next();
//			System.out.println(e.getName());
			//獲取id屬性
			Attribute id = e.attribute("id");
			System.out.println(id.getName()+ "=" + id.getValue());
			//獲取student的子元素
			Element name = e.element("name");
			Element course = e.element("course");
			Element score = e.element("score");
			System.out.println(name.getName()+ "=" + name.getStringValue());
			System.out.println(course.getName()+ "=" + course.getText());
			System.out.println(score.getName()+ "=" + score.getText());
			System.out.println("----------------------------------");
		}
		
	}
}
發佈了81 篇原創文章 · 獲贊 18 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章