创建XML文件
程序员文章站
2022-05-02 17:46:21
...
用java类创建一个XML文件
要生成的xml文件数据
<students>
<student sno="1">
<sname>易大师</sname>
</student>
<student sno="2">
<sname>德玛西亚</sname>
</student>
</students>
实现过程
public static void main(String[] args) throws IOException {
List<Student> list = new ArrayList<Student>();
list.add(new Student("易大师",1));
list.add(new Student("德玛西亚",2));
//创建文档对象
Document doc = DocumentHelper.createDocument();
//向文档中添加根元素
Element root = doc.addElement("students");
//遍历根元素下的学生对象
for (Student s : list) {
Element stuNode = root.addElement("student").addAttribute("sno", s.getSno() + "");
stuNode.addElement("sname").setText(s.getName());
}
File f = new File("dom5/src/stuInfo.xml");
System.out.println(f.getAbsolutePath());
//准备输出流对象
FileWriter fw = new FileWriter(f);
//设置输出格式
OutputFormat fmt = OutputFormat.createPrettyPrint();
//构建xml数据输出流
XMLWriter writer = new XMLWriter(fw,fmt);
writer.write(doc);
writer.flush();
writer.close();
}
}