public class StudentBean {
private String sex; //學生性別
private String name; //學生姓名
private int age; //學生年齡
private String phone; //電話號碼
public void setSex(String s) {
sex = s;
}
public void setName(String s) {
name = s;
}
public void setAge(int a) {
age = a;
}
public void setPhone(String s) {
phone = s;
}
public String getSex() {
return sex;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
}
Document doc = null;
try {
doc = db.parse(inFile);
}
catch (DOMException dom) {
System.err.println(dom.getMessage());
System.exit(1);
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
//下面是解析XML的全過程,比較簡單,先取根項目"學生花名冊"
Element root = doc.getDocumentElement();
//取"學生"元素列表
NodeList students = root.getElementsByTagName("學生");
for (int i = 0; i < students.getLength(); i++) {
//依次取每個"學生"元素
Element student = (Element) students.item(i);
//建立一個學生的Bean執行個體
StudentBean studentBean = new StudentBean();
//取學生的性別屬性
studentBean.setSex(student.getAttribute("性別"));
//取"姓名"元素,下面類同
NodeList names = student.getElementsByTagName("姓名");
if (names.getLength() == 1) {
Element e = (Element) names.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setName(t.getNodeValue());
}
NodeList ages = student.getElementsByTagName("年齡");
if (ages.getLength() == 1) {
Element e = (Element) ages.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setAge(Integer.parseInt(t.getNodeValue()));
}
NodeList phones = student.getElementsByTagName("電話");
if (phones.getLength() == 1) {
Element e = (Element) phones.item(0);
Text t = (Text) e.getFirstChild();
studentBean.setPhone(t.getNodeValue());
}
//下面是建立XML文檔內容的過程,先建立根項目"學生花名冊"
Element root = doc.createElement("學生花名冊");
//根項目添加上文檔
doc.appendChild(root);
//取學生資訊的Bean列表
for (int i = 0; i < student_Vector.size(); i++) {
//依次取每個學生的資訊
StudentBean studentBean = (StudentBean) student_Vector.get(i);
//建立"學生"元素,添加到根項目
Element student = doc.createElement("學生");
student.setAttribute("性別", studentBean.getSex());
root.appendChild(student);
//建立"姓名"元素,添加到學生下面,下同
Element name = doc.createElement("姓名");
student.appendChild(name);
Text tName = doc.createTextNode(studentBean.getName());
name.appendChild(tName);
Element age = doc.createElement("年齡");
student.appendChild(age);
Text tAge = doc.createTextNode(String.valueOf(studentBean.
getAge()));
age.appendChild(tAge);
Element phone = doc.createElement("電話");
student.appendChild(phone);
Text tPhone = doc.createTextNode(studentBean.getPhone());
phone.appendChild(tPhone);
}
//把XML文檔輸出到指定的檔案
FileOutputStream outStream = new FileOutputStream(outFile);
OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
( (XmlDocument) doc).write(outWriter, "GB2312");
outWriter.close();
outStream.close();
}
//最後加入測試主函數,如下:
public static void main(String[] args) throws Exception {
//建立測試執行個體
XMLTest xmlTest = new XMLTest();
//初始化向量列表
xmlTest.student_Vector = new Vector();