Java生成xml——JDOM生成

一、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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值