java生成简单的XML格式文件;
引用jar包:jdom.jar
简单测试类:
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class Java2XML {
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
public Student(Integer id,String name,String sex,Integer age){
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
//生成XML
public void BuildXMLDoc() throws IOException, JDOMException {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student(1,"张三","男",18);
list.add(s1);
Student s2 = new Student(2,"李四","女",20);
list.add(s2);
Student s3 = new Student(3,"王五","男",22);
list.add(s3);
// 创建根节点 并设置它的属性 ;
Element root = new Element("students").setAttribute("count", "4");
// 将根节点添加到文档中;
Document Doc = new Document(root);
for (int i = 0; i < list.size(); i++) {
// 创建一级节点 student;
Element oneElements = new Element("student");
//创建二级节点 type
Element twoElements = new Element("type");
//给type节点增加子节点并赋值
twoElements.addContent(new Element("sex").setText(list.get(i).getSex()));
twoElements.addContent(new Element("age").setText(list.get(i).getAge().toString()));
// 给student节点添加子节点并赋值;
oneElements.addContent(new Element("id").setText(list.get(i).getId().toString()));
oneElements.addContent(new Element("name").setText(list.get(i).getName()));
oneElements.addContent(twoElements);
//将节点添加到父节点上
root.addContent(oneElements);
}
// 输出 students.xml 文件;
// 使xml文件 缩进效果
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream("d:/student.xml"));
}
public static void main(String[] args) {
try {
Java2XML j2x = new Java2XML();
System.out.println("正在生成student.xml 文件...");
j2x.BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("d:/student.xml 文件已生成");
}
}
运行结果为: