XML解析之JDOM

一、JDOM是使用Java语言编写的用于读、写、操作XML的一套组件。所谓的JDOM=JDOM的可修改性 + SAX的文件读取性

JDOM的开发包下载地址:http://www.jdom.org/    (找到Binaries,里面有JDOM的版本)


二、JDOM的主要操作类:

No.

类名称

描述

1

Document

Document类定义了一个XML文件的各种操作,用户可以通过它所提供的方法来存取根元素以及存取处理命令文件层次的相关信息。

2

DOMBuilder

DOMBuilder类用来建立一个JDOM结构树

3

Element

Element类定义了一个XML元素的各种操作,用户可以通过他所提供的方法得到元素的文字内容、属性值以及子节点

4

Attribute

Attribute类表示了XML文件元素中属性的各种操作

5

XMLOutputter

XMLOutputter类会将一个JDOM结构树格式化为一个XML文件,并且以输出流的方式加以输出


三、利用JDOM生成XML文件(address.xml)

package he.xiao.wei;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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

public class JDOMBuildFileDemo {
	public static void main(String[] args) {
		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", "10330070");
		//定义Document对象
		Document doc = new Document(addresslist);
		name.setText("Joywy");
		//将属性设置到元素之中
		name.setAttribute(id);
		email.setText("beyondhxw@163.com");
		//设置关系
		linkman.addContent(name);
		linkman.addContent(email);
		addresslist.addContent(linkman);
		XMLOutputter out = new XMLOutputter();
		//设置编码
		out.setFormat(out.getFormat().setEncoding("GBK"));
		try {
			out.output(doc, new FileOutputStream(new File("E:" + File.separator + "address.xml")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

四、JDOM解析address.xml文件

package he.xiao.wei;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class JDOMParseXML {
	public static void main(String[] args) throws Exception{
		SAXBuilder builder = new SAXBuilder();
		Document read_doc = builder.build(new File("E:" + File.separator + "address.xml"));
		//取得根
		Element root = read_doc.getRootElement();
		//得到所有的linkman
		List list = root.getChildren("linkman");
		for(int i = 0; i < list.size(); i++){
			Element e = (Element)list.get(i);
			String name = e.getChildText("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("Email:" + email);
			System.out.println("--------------------");
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值