用Dom4j解析xml(Java版)含jar包

java解析xml有四种方式:
Dom、SAX、DOM4J、JDOM

下面以Dom4j来解析xml文件

先导入两个jar包 dom4j-1.6.1.jarjunit-4.10.jar

package com.g_xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4j {
	public static void main(String[] args) throws FileNotFoundException, DocumentException {
		//1.创建SAXReader解析器
		SAXReader reader = new SAXReader();
		
		//2. 读取要解析的文件,让文件的内容存在 Document中
		Document doc = reader.read(new FileInputStream("city.xml"));
		
		//3. 获取根节点
		Element root = doc.getRootElement();
		
		//4.获取根节点的所有直接子元素
		List<Element> list = root.elements();
		
		//5.遍历所有根节点的直接子元素
		for(Element ele:list) {
			System.out.println(ele.getName()+"--"+ele.attributeValue("name")
			+"--"+ele.attributeValue("postcode"));
		}
		
	}

}

package com.g_xml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * dom4j解析xml
 * @author ylq
 *
 */
public class Dom4jDemo {
	public static void main(String[] args) throws FileNotFoundException, DocumentException {
		getCity();
	}
	
	public static void getCity() throws FileNotFoundException, DocumentException {
		//1.创建SAXReader解析器
		SAXReader reader = new SAXReader();
		
		//2. 读取要解析的文件,让文件的内容存在 Document中
		Document doc = reader.read(new FileInputStream("city.xml"));
		
		//3. 获取根节点
		Element root = doc.getRootElement();
		//5. 遍历所有子节点
		getElements(root);
		
	}
	
	
	/**
	 * 递归遍历所有根节点中的子元素
	 */
	public static void getElements(Element ele){
		List<Element> list = ele.elements();//ele.elements()获取根节点中的直接子元素
		if(list.size() > 0){
			for(Element e : list){
				if(e.getName().equals("province")){
					System.out.print("  省份:  "+e.attributeValue("name"));
					System.out.println("  邮编:  "+e.attributeValue("postcode"));
					
				}else if(e.getName().equals("city")){
					System.out.print("  	市:  "+e.attributeValue("name"));
					System.out.println("  	邮编:  "+e.attributeValue("postcode"));
					
				}else if(e.getName().equals("area")){
					System.out.print("  		区:  "+e.attributeValue("name"));
					System.out.println("  		邮编:  "+e.attributeValue("postcode"));
					
				}
				//递归调用
				getElements(e);
			}
		}
	}
	
	

}

city.xml和两个jar包,需要的朋友自己拿哦!
链接:https://pan.baidu.com/s/1iFtEoESieSzp0_8HXnicYA
提取码:6s25

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值