1、首先,在资源网站下载JDOM插件。在工程中加载JDOM_XX.jar。
package test;import java.io.FileOutputStream; import java.io.IOException; import java.util.List;import oracle.net.aso.p;import org.jdom2.Attribute; import org.jdom2.Comment; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter;import com.actionform.StudentForm; import com.dao.imp.StudentDAO;public class JDomOutput {public static void main(String[] args) throws IOException{//创建文档Document document = new Document();//创建根元素Element people = new Element("people");//把根元素加入到document中 document.addContent(people); //创建注释Comment rootComment = new Comment("将数据从程序输出到XML中!");people.addContent(rootComment);//创建父元素Element person1 = new Element("person");//把元素加入到根元素中 people.addContent(person1);//设置person1元素属性 person1.setAttribute("id", "001");Attribute person1_gender = new Attribute("gender", "male");person1.setAttribute(person1_gender);Element person1_name = new Element("name");person1_name.setText("刘德华");person1.addContent(person1_name);Element person1_address = new Element("address");person1_address.setText("香港");person1.addContent(person1_address);Element person2 = new Element("person");people.addContent(person2); person2.setAttribute("id", "002").setAttribute("gender","male");//添加属性,可以一次添加多个属性 Element person2_name = new Element("name");person2_name.setText("林志颖");person2.addContent(person2_name); Element person2_address = new Element("address");person2_address.setText("台湾");person2.addContent(person2_address);StudentDAO studentDAO = new StudentDAO(); //自己编写daoList<StudentForm> result = studentDAO.getAllStudent();if (result!=null) {for (StudentForm student:result) {int i=0;Element[] person=new Element[result.size()];person[i]= new Element("person");people.addContent(person[i]); person[i].setAttribute("id", "1.1").setAttribute("gerder", "male");Element person_name=new Element("sname");person_name.setText(student.getSname());person[i].addContent(person_name);Element person_birthday = new Element("address");person_birthday.setText(student.getBirthday().toString());person[i].addContent(person_birthday);i++;}}//设置xml输出格式Format format = Format.getPrettyFormat();format.setEncoding("utf-8");//设置编码format.setIndent(" ");//设置缩进//得到xml输出流XMLOutputter out = new XMLOutputter(format);//把数据输出到xml中out.output(document, new FileOutputStream("jdom.xml"));//或者FileWriter } }