package day0712;
import java.io.FileWriter;
import java.io.IOException;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class BuildxmlDemo {
public static void main(String[] args) {
buildXml("src/mybooks.xml");
}
public static void buildXml(String filename) {
String [][] books = {
{"1001","武侠","天龙八部","金庸","60","1965","zh"},
{"1002","武侠","天涯明月刀","古龙","45","1969","zh"},
{"1003","科幻","哈利波特","Rowling","86","2005","en"},
{"1004","web","Struts","bruce","90","2011","en"}
};
// System.out.println(books[0][2]); 必须以二维数组形式输出
// System.out.println(books[0][3]);
// System.out.println(books[0][4]);
// System.out.println(books[0][5]);
// System.out.println("********************");
Document doc = DocumentHelper.createDocument();
Element rootElmt = doc.addElement("booklist");
for(String[] book : books){
Element bookElmt = rootElmt.addElement("book");
Element titleElmt = bookElmt.addElement("title");
Element authorElmt = bookElmt.addElement("author");
Element priceElmt = bookElmt.addElement("price");
Element yearElmt = bookElmt.addElement("year");
titleElmt.setText(book[2]);
authorElmt.setText(book[3]);
priceElmt.setText(book[4]);
yearElmt.setText(book[5]);
// System.out.println(book[2]);
// System.out.println(book[3]);此处可以输出,注意for增强循环二维数组转化为一位数组的方法
// System.out.println(book[4]);
// System.out.println(book[5]);
// System.out.println("*********************");
bookElmt.addAttribute("isbn", book[0]);
bookElmt.addAttribute("catalog", book[1]);
titleElmt.addAttribute("lang", book[6]);
}
outputXml(doc, filename);
}
private static void outputXml(Document doc, String filename) {
try {
FileWriter fw = new FileWriter(filename);
OutputFormat format
= OutputFormat.createPrettyPrint();
format.setEncoding("gb2312");
XMLWriter xmlWriter
= new XMLWriter(fw, format);
xmlWriter.write(doc);
xmlWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
生产文件:
<?xml version="1.0" encoding="gb2312"?>
<booklist>
<book isbn="1001" catalog="武侠">
<title lang="zh">天龙八部</title>
<author>金庸</author>
<price>60</price>
<year>1965</year>
</book>
<book isbn="1002" catalog="武侠">
<title lang="zh">天涯明月刀</title>
<author>古龙</author>
<price>45</price>
<year>1969</year>
</book>
<book isbn="1003" catalog="科幻">
<title lang="en">哈利波特</title>
<author>Rowling</author>
<price>86</price>
<year>2005</year>
</book>
<book isbn="1004" catalog="web">
<title lang="en">Struts</title>
<author>bruce</author>
<price>90</price>
<year>2011</year>
</book>
</booklist>