接着上一篇的dom4j解析xml文档,现在来简单写下dom4j如何生成xml文档,当然需要上一篇中提供的(dom4j.1.6.1.jar jar包,以及实体类Book.java和解析xml文档类ReadXMLFile.java。
1 dom4j生成xml文档
package com.wnq.sk.dom4jXML01;
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* dom4j生成xml文档
* @author liandong
*/
public class CreateXMLFile
{
public static void main(String[] args)
throws Exception
{
List<Book> books = ReadXMLFile.ReadXMLFile("books.xml");
String fileName = "dom4j_create_books.xml";
createXMLFile(books, fileName);
}
public static void createXMLFile(List<Book> books, String fileName)
throws Exception
{
// 分别创建文档,根节点,然后把根节点添加到文档
Document document = DocumentHelper.createDocument();
Element rooteElement = DocumentHelper.createElement("bookstore");
document.setRootElement(rooteElement);
/**
* 创建文档,并且设置文档的根节点 Element root = DocumentHelper.createElement("bookstore"); Document document =
* DocumentHelper.createDocument(root);
*/
for(int i=0;i<books.size();i++){
Element bookElement=rooteElement.addElement("book");
bookElement.addAttribute("category", books.get(i).getCategory());
Element titleElement=bookElement.addElement("title");
titleElement.addAttribute("lang", books.get(i).getTitleLang());
titleElement.setText(books.get(i).getTitle());
String[] authors = books.get(i).getAuthor().split("/");
for (int j = 0; j < authors.length; j++)
{
Element authorElement = bookElement.addElement("author");
authorElement.setText(authors[j]);
}
Element yearElement = bookElement.addElement("year");
yearElement.setText(books.get(i).getYear().toString());
Element priceElement = bookElement.addElement("price");
priceElement.setText(books.get(i).getPrice().toString());
}
OutputFormat outputFormat = new OutputFormat(" ", true);
XMLWriter xmlWriter = new XMLWriter(new FileWriter(new File(fileName)), outputFormat);
xmlWriter.write(document);
// 一定要刷新
xmlWriter.flush();
System.out.println("dom4j生成xml文档成功!");
}
}
2 运行结果
到此dom,sax,jdom,dom4j四种解析并生成xml文档的小实例已经基本写好。有什么错误的地方,还请大家批评指正。