导入dom4j.jar包
?
<?xml version="1.0" encoding="UTF-8"?> <bodys> <body id="1" name="贵州"> <yy id="01">贵阳</yy> <yy id="02">都匀</yy> </body> <body id="2" name="重庆"> <yy id="">万州</yy> <yy>沙坪坝</yy> </body> </bodys>
?
?
?
import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Dom4j { public static void reader(String id){ //创建读取 SAXReader read=new SAXReader(); try { //读取xml文件 返回文档对象 Document doc=read.read("xml/body.xml"); //获取根节点 Element root=doc.getRootElement(); //获取节点中的数据 返回一个list(获取所有的省) List<Element> elements =root.elements(); for(Element e:elements){ System.out.println(e.attributeValue("id")+":"+e.attributeValue("name")); //判断编号是否等于传递上来参数 if(e.attributeValue("id").equals(id)){ //获取省下市 List<Element> list=e.elements(); for(Element et:list){ System.out.println(et.attributeValue("id")+":"+et.getText()); } } } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { ABC.reader(1+""); } }
?
?
原文:http://lqi.iteye.com/blog/2154225