package xml; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.XMLWriter; public class WriteXML { public static void main(String[] args) { List<Student> list = new ArrayList<Student>(); list.add(new Student("小明", 20, "农", 76)); list.add(new Student("小周", 18, "一中", 560)); list.add(new Student("明", 17, "中学", 444)); Document doc = DocumentHelper.createDocument(); Element root = doc.addElement("list"); for(Student stu : list){ Element subEle = root.addElement("student"); subEle.addElement("name").addText(stu.getName()); subEle.addElement("age").addText(stu.getAge()+""); subEle.addElement("school").addText(stu.getSchool()); subEle.addElement("score").addText(stu.getScore()+""); } try { XMLWriter writer = new XMLWriter(new FileOutputStream("stu.xml")); writer.write(doc); writer.close(); System.out.println("写出完毕"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行结果:
主要的代码:
Document doc = DocumentHelper.createDocument(); Element root = doc.addRootElement("list"); for(Student stu : list){ Element ele = root.addElement("student"); ele.addElement("name").addText(stu.getName()); ele.addElement("age").addText(stu.getAge()); ele.addElement("school").addText(stu.getScholl()); ele.addElement("score").addText(stu.getScore()); } XMLWriter writer = new XMLWriter(new FileOutputStream("stu.xml")); writer.write(doc); writer.close();