Java生成xml——JDOM生成

来源:互联网 发布:cs网络对战连不上 编辑:程序博客网 时间:2024/06/08 06:06

一、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>



0 0
原创粉丝点击