import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class CreateXML {
Book[] books = new Book[] { new Book("1", "唐诗三百首"),
new Book("2", "Think in Java"), new Book("3", "神雕侠侣"),
new Book("4", "葵花宝典") };
public void buildXMLDoc() throws IOException, JDOMException {
// 创建根节点 并设置它的属性 ;
Element root = new Element("books").setAttribute("count", "4");
// 将根节点添加到文档中;
Document doc = new Document(root);
for (int i = 0; i < books.length; i++) {
// 创建节点 book;
Element elements = new Element("book");
// 给 book 节点添加子节点并赋值;
elements.addContent(new Element("id").setText(books[i].getId()));
elements.addContent(new Element("name").setText(books[i].getName()));
//
root.addContent(elements);
}
// 输出 books.xml 文件;
// 使xml文件 缩进效果
Format format = Format.getPrettyFormat();
XMLOutputter xmlOut = new XMLOutputter(format);
xmlOut.output(doc, new FileOutputStream("c:/books.xml"));
}
public static void main(String[] args) {
try {
CreateXML createXML = new CreateXML();
System.out.println("正在生成 books.xml 文件...");
createXML.buildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("c:/books.xml 文件已生成");
}
class Book {
private String id;
private String name;
public Book(String id, String name) {
super();
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}