①Book实体类
package com.yealink.phonebook.pojo;
/**
* Created by yl1794 on 2018/5/14.
*/
public class Book {
private String id;
private String name;
public Book(String id, String name) {
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;
}
}
②DOM方式生成xml文件
package com.yealink.phonebook;
import java.io.IOException;
import java.io.FileOutputStream;
import com.yealink.phonebook.pojo.Book;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
* Created by yl1794 on 2018/5/14.
*/
public class Java2XML {
Book[] books = new Book[]
{
new Book("1","SpringBoot 实战"),
new Book("2","深入理解JAVA虚拟机"),
new Book("3","人人都是产品经理"),
new Book("4","JavaScript语言精粹")
};
public void BuildXMLDoc() throws IOException{
// 创建根节点 并设置它的属性 ;
Element root = new Element("books").setAttribute("count", "4");
// 将根节点添加到文档中;
Document Doc = new Document(root);
for (Book book : books) {
// 创建节点 book;
Element elements = new Element("book");
// 给 book 节点添加子节点并赋值;
elements.addContent(new Element("id").setText(book.getId()));
elements.addContent(new Element("name").setText(book.getName()));
//
root.addContent(elements);
}
// 输出 books.xml 文件;
// 使xml文件 缩进效果
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream("E:\\idea/books.xml"));
}
public static void main(String[] args) {
try {
Java2XML j2x = new Java2XML();
j2x.BuildXMLDoc();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("文件已生成");
}
}
③结果如下