日期:2014-05-20 浏览次数:20805 次
import org.jdom.Element; import org.jdom.Document; import org.jdom.output.XMLOutputter; import java.util.List; import java.util.ArrayList; import java.io.File; import java.io.FileOutputStream; /** * Created by IntelliJ IDEA. * User: Administrator * Date: 2011-9-18 * Time: 11:36:25 * To change this template use File | Settings | File Templates. */ public class DeptInfo { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<EmpInfo> getEmps() { return emps; } public void setEmps(List<EmpInfo> emps) { this.emps = emps; } private List<EmpInfo> emps; public void saveToXML(File file){ Element root=new Element("DeptInfo"); Document document=new Document(root); Element id=new Element("id"); id.setText(this.getId()); Element name=new Element("name"); name.setText(this.getName()); Element empInfos=new Element("empInfos"); for(EmpInfo ei:this.getEmps()){ Element empInfo=new Element("empInfo"); Element empId=new Element("id"); empId.setText(ei.getId()); Element empName=new Element("name"); empName.setText(ei.getName()); empInfo.addContent(empId); empInfo.addContent(empName); empInfos.addContent(empInfo); } // List<Element> list=new ArrayList<Element>(); // list.add(env1); // list.add(env2); root.addContent(id); root.addContent(name); root.addContent(empInfos); org.jdom.output.Format format = org.jdom.output.Format.getCompactFormat(); format.setEncoding("UTF-8"); format.setIndent(" "); try { XMLOutputter outputter = new XMLOutputter(format); outputter.output(document, new FileOutputStream(file)); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args){ EmpInfo ei1=new EmpInfo("1","ei1"); EmpInfo ei2=new EmpInfo("2","ei2"); EmpInfo ei3=new EmpInfo("2","ei3"); DeptInfo di=new DeptInfo(); di.setId("1"); di.setName("di1"); List<EmpInfo> list=new ArrayList<EmpInfo>(); list.add(ei1); list.add(ei2); list.add(ei3); di.setEmps(list); di.saveToXML(new File("E:\\deptInfo.xml")); } }