這支程式的任務很明確:讀取 company.XML,把每個 employee 標籤下的資訊封裝成 Employee 物件,最後以 id 為鍵收進 HashMap 中,方便後續查詢。
package coresun.cn;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import java.io.*;
import java.util.*;
public class DOMEmployee1 {
public static void main(String[] args) {
HashMap<String, Employee> map = new HashMap<String, Employee>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
// 解析 company.XML,取得文件節點
Document document = db.parse(new File("company.XML"));
// 由文件節點取得根元素
Element root = document.getDocumentElement();
// 取得所有 employee 節點的集合
NodeList nl = root.getElementsByTagName("employee");
for (int i = 0; i < nl.getLength(); i++) {
Employee e = new Employee();
// 取出 employee 元素
Element n = (Element) nl.item(i);
// 讀取 employee 元素的屬性
String id = n.getAttribute("id");
String sex = n.getAttribute("sex");
e.setId(id);
e.setSex(sex);
// 讀取 name 元素的值
Element name = (Element) n.getElementsByTagName("name").item(0);
Text nameText = (Text) name.getChildNodes().item(0);
e.setName(nameText.getData().trim());
// 讀取 age 元素的值
Element age = (Element) n.getElementsByTagName("age").item(0);
Text ageText = (Text) age.getChildNodes().item(0);
String sAge = ageText.getData().trim();
e.setAge(Integer.parseInt(sAge));
// 讀取 interest 元素的值(可能有多個,也可能完全沒有)
NodeList interestList = n.getElementsByTagName("interest");
String[] interestStringArray = new String[interestList.getLength()];
for (int j = 0; j < interestList.getLength(); j++) {
Element in = (Element) interestList.item(j);
Text interestText = (Text) in.getChildNodes().item(0);
interestStringArray[j] = interestText.getData();
}
e.setInterest(interestStringArray);
// 讀取 salary 元素的值
NodeList salaryList = n.getElementsByTagName("salary");
Element salaryElement = (Element) salaryList.item(0);
NodeList salaryChild = salaryElement.getChildNodes();
for (int j = 0; j < salaryChild.getLength(); j++) {
Node nSalaryChild = salaryChild.item(j);
// 只處理元素節點,跳過純文字與空白節點
if (nSalaryChild instanceof Element) {
Text salaryText = (Text) nSalaryChild.getChildNodes().item(0);
String sSalary = salaryText.getData();
e.setSalary(Float.parseFloat(sSalary));
}
}
// 以 id 為 key 放入 HashMap
map.put(id, e);
}
System.out.println(map);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package coresun.cn;
public class Employee {
private String id;
private String sex;
private String name;
private int age;
private float salary;
private String[] interest;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
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; }
public float getSalary() { return salary; }
public void setSalary(float salary) { this.salary = salary; }
public String[] getInterest() { return interest; }
public void setInterest(String[] interest) { this.interest = interest; }
// 重新定義 toString(),方便直接列印物件內容
public String toString() {
return "id=" + this.id
+ " sex=" + this.sex
+ " name=" + this.name
+ " salary=" + this.salary
+ " interest=" + this.interest;
}
}
DOM 的解析流程其實很固定:透過 DocumentBuilderFactory 取得 DocumentBuilder,呼叫 parse() 得到 Document,再用 getDocumentElement() 拿到根元素,接著就能用 getElementsByTagName() 或 getChildNodes() 往下走訪。
這個範例裡有兩個值得留意的細節。第一,屬性用 getAttribute() 直接取值,而元素內的文字則需要多繞一層:先取得元素,再從它的子節點中取出 Text 節點並呼叫 getData()——這是 DOM 把「元素」與「文字」視為不同節點所帶來的必然結果。第二,走訪 salary 的子節點時,務必用 instanceof Element 過濾,因為 XML 中為了排版而產生的空白與換行也會被解析成文字節點,若不過濾就會在轉型時出錯。