dom4j解析xml文件

使用dom4j解析xml文件

xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<fruits name="水果" name2="还是水果">
	<fruit name = "苹果">
		<color>青色</color>
		<price>3.5</price>
	</fruit>
	<fruit name = "梨">
		<color>黄色</color>
		<price>2.5</price>
	</fruit>
</fruits>


Java代码:

/**
	 * 根据文件路径返回一个Document对象
	 * @param path
	 * @return
	 * @throws DocumentException
	 */
	public Document loadXML(String path) throws DocumentException{
		SAXReader sax = new SAXReader();
		Document docm = null;
		docm = sax.read(path);
		return docm;
	}

	
	public void sayXMl(String path) throws DocumentException{
		Document docm = loadXML(path);
		// 获取根节点
		Element rootElt = docm.getRootElement(); 
		//获取根节点名称
		String rootName = rootElt.getName();
		System.out.println("根节点名称:"+rootName);
		System.out.println("根节点text:"+rootElt.getTextTrim());
		
		//获取根节点的所有属性值集合
		List list = rootElt.attributes(); 
		for(Object ob:list){
			Attribute temp = (Attribute) ob;
			String str = temp.getName() + "-->value:" +temp.getValue();
			System.out.println("根节点Attribute:"+str);
		}
		
		//获取根节点的所有的fruit节点的迭代
		Iterator i = rootElt.elementIterator("fruit"); 
		while(i.hasNext()){
			Element itemEle = (Element) i.next();
			//获取fruit节点下面的color节点的值
			String color = itemEle.elementTextTrim("color"); 
			//获取fruit节点下面的price节点的值
			String price = itemEle.elementTextTrim("price");
			//获取fruit节点的name属性值
			String name = itemEle.attributeValue("name");
			System.out.println("fruit:"+name+":  color-->"+color+"    price-->"+price+"");
		}
	}



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值