废话就不多说了,直接写代码了。
用到的XML文件:
<?xml version="1.0" encoding="utf-8"?>
<PHONE>
<PHONE_BRAND>
<PHONE_BRAND_CODE>1-2</PHONE_BRAND_CODE>
<PHONE_BRAND_NAME>ABC</PHONE_BRAND_NAME>
<PHONE_BRAND_COMPANY>DEF</PHONE_BRAND_COMPANY>
<PHONE_BRAND_PLACE>GHJ</PHONE_BRAND_PLACE>
</PHONE_BRAND>
</PHONE>
JAVA代码如下:
package com.XMLTest.test;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public class TestTwo {
public static void main(String[] args) {
//使用的jdom时首先要确定使用什么解析器(下边是使用默认解析器)
org.jdom.input.SAXBuilder builder = new SAXBuilder(false);
//Document对象
Document doc = null;
//Element对象 每个节点都是一个Element对象 其子节点也是Element对象。
Element element = null;
try {
//用默认解析器解析电脑上的XML文件,并把解析出来的数据赋给 doc
doc = builder.build("E:/Test/test.xml");
//每个节点都是一个Element对象,根节点也是
element = doc.getRootElement();
//得到根节点下的PHONE_BRAND集合
List<Element> list = element.getChildren("PHONE_BRAND");
//循环取出集合中的数据
for(Element pb : list){
System.out.println("编码:" + pb.getChild("PHONE_BRAND_CODE").getValue());
System.out.println("名称:" + pb.getChild("PHONE_BRAND_NAME").getValue());
System.out.println("公司:" + pb.getChild("PHONE_BRAND_COMPANY").getValue());
System.out.println("地点:" + pb.getChild("PHONE_BRAND_PLACE").getValue());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
输出结果如下图: