1.背景:
上一篇关于XML 的文章<<java 解析dom 树方式来解析XML文件>> http://blog.youkuaiyun.com/nx188/article/details/51417535 , 说的是java 解析XML,
本文是java 代码将java bean 转化生成XML 文件
2.用的 jar 包是
jdom.jar
3.代码:
package XMLGenerate;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class Java2XmlFile {
private Book books[] = {
new Book("1","入门"),
new Book("2","thinking in java"),
new Book("3","数据结构"),
new Book("4","算法到了")
};
public void formatXML() throws FileNotFoundException, IOException{
Element root = new Element("books").setAttribute("count", "4");
Document doc = new Document(root);
for(int i=0;i<books.length;i++) {
Element bookElement = new Element("book");
bookElement.addContent(new Element("id").setText(books[i].getId()));
bookElement.addContent(new Element("name").setText(books[i].getName()));
root.addContent(bookElement);
}
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(doc, new FileOutputStream("books.xml"));
}
public static void main(String[] args) throws FileNotFoundException, IOException {
Java2XmlFile java2XmlFile = new Java2XmlFile();
java2XmlFile.formatXML();
System.out.println("xml 文件已生成");
}
}
//实体类
class Book {
private String id;
private String name ;
public Book(String id, String name) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
生成的books.xml 文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<books count="4">
<book>
<id>1</id>
<name>入门</name>
</book>
<book>
<id>2</id>
<name>thinking in java</name>
</book>
<book>
<id>3</id>
<name>数据结构</name>
</book>
<book>
<id>4</id>
<name>算法到了</name>
</book>
</books>