一、JDOM生成实例
JDomToXmlDemo.java
public class JDomToXmlDemo {
public static void main(String[] args) {
//1、新建根节点
Element root = new Element("bookstore");
//2、创建Document对象,将根节点写入对象中
Document document = new Document(root);
//3、新建book节点
Element book = new Element("book");
//4、设置属性
book.setAttribute("id", "1");
//5、将book节点添加到根节点下
root.addContent(book);
//6、新建book的子节点
Element name = new Element("name");
//7、设置子节点文本内容
name.setText("冰与火之歌");
//8、将子节点添加到book节点下
book.addContent(name);
Element author = new Element("author");
author.setText("乔治马丁");
book.addContent(author);
Element time = new Element("time");
time.setText("2014");
book.addContent(time);
Element price = new Element("price");
price.setText("60");
book.addContent(price);
//9、设置输出格式为带换行和缩进的格式
Format format = Format.getPrettyFormat();
//10、新建输出对象
XMLOutputter out = new XMLOutputter(format);
try {
//11、输出xml文件
out.output(document, new FileOutputStream(new File("xml/jdomToXml.xml")));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
生成jdomToXml.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<time>2014</time>
<price>60</price>
</book>
</bookstore>