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();