/** * @(#)T3_xml.java * * * @author Xie Xiaojin * @version 1.00 2009/11/4 */ import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.apache.crimson.tree.XmlDocument; public class T3_xml { private DocumentBuilderFactory factory; private DocumentBuilder builder; private Document doc; private Vector<Student> vector; public T3_xml() { } public T3_xml(Vector v){ this.vector = v; } public void writeXML(String file) throws Exception { factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); doc = builder.newDocument(); Element root = doc.createElement("学生名册"); doc.appendChild(root); for(int i = 0; i < vector.size(); i++){ Student stu = (Student)(vector.get(i)); Element student = doc.createElement("学生"); student.setAttribute("学号", String.valueOf(stu.getId())); Element name = doc.createElement("姓名"); name.appendChild(doc.createTextNode(stu.getName())); student.appendChild(name); Element depart = doc.createElement("院系"); depart.appendChild(doc.createTextNode(stu.getDepart())); student.appendChild(depart); Element score = doc.createElement("成绩"); score.appendChild(doc.createTextNode(String.valueOf(stu.getScore()))); student.appendChild(score); root.appendChild(student); } System.out.println("写入文件" + file + "..."); OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file)); ((XmlDocument)doc).write(out, "GB2312"); out.flush(); System.out.println("写入完毕!"); out.close(); } public void setVector(Vector v){ this.vector = v; } public static void main(String[] args) throws Exception { T3_xml t = new T3_xml(); Vector<Student> students = new Vector<Student>(); students.add(new Student(200731102076L, "Xie Xiaojin", "Computer Science & Technology School", 84)); students.add(new Student(200731102077L, "Cai Fan", "Computer Science & Technology School", 85)); students.add(new Student(200731102078L, "Xia Haibin", "Computer Science & Technology School", 86)); students.add(new Student(200731102079L, "Wu Dianyu", "Computer Science & Technology School", 87)); t.setVector(students); t.writeXML("Student.xml"); } } 结果生成一个Student.xml文档: <?xml version="1.0" encoding="GB2312"?> <学生名册> <学生 学号="200731102076"> <姓名>Xie Xiaojin</姓名> <院系>Computer Science & Technology School</院系> <成绩>84</成绩> </学生> <学生 学号="200731102077"> <姓名>Cai Fan</姓名> <院系>Computer Science & Technology School</院系> <成绩>85</成绩> </学生> <学生 学号="200731102078"> <姓名>Xia Haibin</姓名> <院系>Computer Science & Technology School</院系> <成绩>86</成绩> </学生> <学生 学号="200731102079"> <姓名>Wu Dianyu</姓名> <院系>Computer Science & Technology School</院系> <成绩>87</成绩> </学生> </学生名册>