JavaWeb - XML解析 - JDOM

来源:互联网 发布:数据分发服务器 编辑:程序博客网 时间:2024/06/06 11:45

JDOM = DOM的可修改性 + SAX的文件读取性

JDOM是一个开源组件,下载地址 ↓

http://www.jdom.org/

如果你看不懂英文,点击这里 ↓ 就是下载页面

http://www.jdom.org/dist/binary/archive/

下载解压缩,找到jdom-*.jar,拷贝到Tomcat目录下lib文件夹里即可。

如果想直接使用,则需要配置classpath

通过JDOM输出XML(JDOM中对DOM解析的支持)

import org.jdom.* ;import org.jdom.output.* ;import java.io.* ;public class demo{public static void main(String args []) throws Exception {Element addresslist = new Element("addresslist") ;Element linkman = new Element("linkman") ;Element name = new Element("name") ;Element email = new Element("email") ;Attribute id = new Attribute("id", "001") ;Document doc = new Document(addresslist) ;// 定义Document对象name.setText("W_Jp") ;name.setAttribute(id) ;// 将属性设置到元素之中email.setText("271953489@qq.com") ;linkman.addContent(name) ;// 设置关系linkman.addContent(email) ;addresslist.addContent(linkman) ;XMLOutputter out = new XMLOutputter() ;out.setFormat(out.getFormat().setEncoding("GBK")) ;// 表示的是设置编码out.output(doc, new FileOutputStream(new File("e:" + File.separator + "JDOM.xml"))) ;}}

通过JDOM读取XML(JDOM中对SAX解析的支持)

import org.jdom.* ;import org.jdom.input.* ;import java.util.* ;import java.io.* ;public class demo{public static void main(String args []) throws Exception {SAXBuilder builder = new SAXBuilder() ;Document read_doc = builder.build("e:" + File.separator + "02.xml") ;Element root = read_doc.getRootElement() ;// 取得根List list = root.getChildren("linkman") ;// 取得所有的linkmanfor(int i=0; i<list.size(); i++){Element e = (Element)list.get(i) ;String name = e.getChildText("name") ;// 得到name子节点的内容String id = e.getChild("name").getAttribute("id").getValue() ;String email = e.getChildText("email") ;System.out.println("-----------------联系人-----------------") ;System.out.println("姓名:" + name + ", 编号:" + id) ;System.out.println("E-Mail:" + email) ;System.out.println("----------------------------------------") ;System.out.println() ;}}}

同类使用工具DOM4j,基本相同,但是DOM4j在某些方面效率比JDOM高

0 0
原创粉丝点击