上一篇我们讲述了dom4j读取xml的4种方法,甚是精彩,那么怎么样写入xml呢?我们直接看下源码实现。
public static void main(String[] args) throws Exception {
// 创建文档
Document document = DocumentHelper.createDocument();
// 设置编码
document.setXMLEncoding("GBK");
// 创建根节点
Element root = document.addElement("students");
// 创建xmlns xml namespace
root.addNamespace("", "http://www.abc.com/ns/test");
root.addNamespace("t", "http://www.abc.com/ns/test");
root.addNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
// 创建属性
root.addAttribute("xsi:schemaLocation",
"http://www.abc.com/ns/test student.xsd");
// 创建对象数组
Student[] s = new Student[5];
// 创建对象
s[0] = new Student("001", "za", "za@163.com", 50, 19, true);
s[1] = new Student("002", "zb", "zb@163.com", 51, 20, true);
s[2] = new Student("003", "zc", "zc@163.com", 52, 21, true);
s[3] = new Student("004", "zd", "zd@163.com", 53, 22, true);
s[4] = new Student("005", "ze", "ze@163.com", 54, 23, true);
// 写入对象
for (int i = 0; i < s.length; i++) {
Student stu = s[i];
// 创建根节点
Element e1 = root.addElement("student",
"http://www.abc.com/ns/test");
// 添加子元素
e1.addElement("id").addText(stu.getId());
e1.addElement("name").addText(stu.getName());
e1.addElement("email").addText(stu.getEmail());
e1.addElement("gender").addText(stu.getGender() ? "男" : "女");
e1.addElement("age").addText("" + stu.getAge());
e1.addElement("java").addText("" + stu.getJava());
}
// 创建输出流
FileOutputStream fos = new FileOutputStream("student.xml");
// 设置编码
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
OutputFormat of = new OutputFormat();
of.setEncoding("GBK");
of.setIndent(true);
of.setIndent(" ");
of.setNewlines(true);
// 写入文件
XMLWriter writer = new XMLWriter(osw, of);
writer.write(document);
writer.close();
}
以上代码言简意赅。大家可以自己写写调试下。
本站文章为宝宝巴士)