[size=xx-large][color=red]JDOM是专门用于Java读取 XML 文档的一种技术,记住这个技术只能读取 XML 文档, 并且需要第三方jar包!在下面提供[/color][/size]
下面是在当前目录下(也就是与sre同级的目录下)产生的 XML 文档,这里一定注意字符集!
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>