使用 JDOM 编写一个 XML 文档(一)

[size=xx-large][color=red]JDOM是专门用于Java读取 XML 文档的一种技术,记住这个技术只能读取 XML 文档, 并且需要第三方jar包!在下面提供[/color][/size]



package com.syh.xml.jdom;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom.Attribute;
import org.jdom.Comment;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
* 编写一个 XML 文档 ---> 将内存中的信息输出到文档中
* @author Administrator
*
*/

public class JDomTest1 {

public static void main(String[] args) throws Exception {

//构造出一个 Document 对象 , 它对应于 整个 XML 文档
Document document = new Document() ;

//构造出一个根元素节点
Element root = new Element("root") ;

//增加一个元素,将其设置为根元素
document.addContent(root) ;

Comment comment = new Comment("This is my comments") ;

//将 注释 增加到 根元素中
root.addContent(comment) ;

Element e = new Element("hello") ;

//为元素增加一个属性
e.setAttribute("google","www.google.com") ;

//将 hello 增加为根元素的一个子元素
root.addContent(e) ;

Element e2 = new Element("world") ;

//创建并声明一个属性
Attribute attr = new Attribute("test", "hehe") ;

//为元素增加一个属性
e2.setAttribute(attr) ;

e.addContent(e2) ;

//另外一中增加属性的方式---> 方法链编程风格
e2.addContent(new Element("aaa").setAttribute("a", "b")
.setAttribute("x", "y").setAttribute("gg", "mm").setText("text content")) ;

//默认的风格,所有内容都在一行,一般使用在网络传输。可以减少网络传输的数据量
Format format = Format.getRawFormat() ;
//优化 XML 文档输出的格式
Format format2 = Format.getPrettyFormat() ;

//自定义 标签前面有多少空格!表示缩进----这个标签仅限于非根节点标签
format2.setIndent(" ") ;

//自定义 XML 文档的编码格式
format2.setEncoding("GBK") ; // 这种方式最好不要使用

XMLOutputter out = new XMLOutputter(format2) ;

//将 根元素 输出到指定的位置上!---> 这个就是文档的输出
out.output(document, new FileOutputStream("jdom.xml")) ;
//上面的代码或者可以使用--> out.output(document, new FileWriter("jdom.xml")) ;

}

}



下面是在当前目录下(也就是与sre同级的目录下)产生的 XML 文档,这里一定注意字符集!


<?xml version="1.0" encoding="GBK"?>
<root>
<!--This is my comments-->
<hello google="www.google.com">
<world test="hehe">
<aaa a="b" x="y" gg="mm">text content</aaa>
</world>
</hello>
</root>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值