xml文件的dom解析


dom解析xml,會一次性讀入xml文件,會把文件中的所有元素,解析成一個個Node對象節點。dom解析是基於樹和節點的文檔,通過操作節點的相關方法,可以獲取節點的屬性,節點的內容,也可以獲節點的子節點,如此便可以對xml文件進行解析。
所以說dom解析便於操作,可以輕鬆完成增刪改查,不過dom解析的文檔不適合過大,由於它是將文檔讀入內存之中,過大的文件影響了機器性能,甚至容易導致內存溢出
Node對象提供了很多常量,表示當前結點的類型,基於Node對象的操作會相對比較複雜,所以我們可以把Node轉成其對應子類,子類裏提供了很多便捷的方法去獲取數據。如把Node類型的對象轉成Element對象。
以下是一個person.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<persons>
	<person id="328">
		<name>zhangsan</name>
		<age>23</age>
	</person>
	<person id="303">
		<name>lisi</name>
		<age>22</age>
	</person>
</persons>
對應的Person封裝類,將讀取的數據封裝成Person類:
public class Person {
	private int id;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	public Person(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Person() {
		super();
	}
}


在使用java api對xml文件進麼解析的時候,由於解析xml文件的方式相對較多,類名相同的相關類也比較多,所以導包的時候要多注意,以免造成不必要的錯誤。
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DomTest {

	public static void main(String[] args) {
		List<Person> list = new DomTest().parsePersons();
		//打印讀取的結果。
		for (Person p : list) {
			System.out.println(p);
		}

	}
	
	//解析xml文件,並把結果封裝至Person的集合中返回
	private List<Person> parsePersons() {
		List<Person> persons = null;
		try {
			//獲得dom製造工廠
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			//獲得dom解析器
			DocumentBuilder builder = factory.newDocumentBuilder();
			//獲得xml文件的輸入流
			InputStream inStream = DomTest.class.getClassLoader()
					.getResourceAsStream("person.xml");
			//通過解析器得到Document對象
			Document document = builder.parse(inStream);
			//得到要獲取的所有person結點,通過每個結點,獲取每個person的內容數據。
			NodeList list = document.getElementsByTagName("person");
			persons = new ArrayList<Person>();
			Person person = null;
			//遍歷person集合,將數據封裝於person對象中
			for (int i = 0, size = list.getLength(); i < size; i++) {
				person = new Person();
				//得到<person>結點
				Element e = (Element) list.item(i);
				//獲取其id屬性
				String id = e.getAttribute("id");
				person.setId(Integer.valueOf(id));
				//得到當前<person>結點的所有孩子結點。
				NodeList chileList = e.getChildNodes();
				//遍歷所有孩子結點,以便獲得其餘數據。
				for (int j = 0, csize = chileList.getLength(); j < csize; j++) {
					Node node = chileList.item(j);
					switch (node.getNodeName()) {
					case "name":
						//當結點爲<name>時,獲取內容,並給person賦值
						String name = node.getTextContent();
						person.setName(name);
						break;
					case "age":
						//當結點爲<age>時,獲取內容,並給person賦值
						String age = node.getTextContent();
						person.setAge(Integer.valueOf(age));
						break;
					}
				}
				//完成一個<person>結點的遍歷,將person對象加入集合中。
				persons.add(person);
				//清空person對象的數據。
				person = null;
			}

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//返回最終得到的數據。
		return persons;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章