解析本地XML文件
public class Demo1 {
public static void main(String[] args) throws IOException, DocumentException {
//1、获取输入流
FileInputStream fis = new FileInputStream("./src/Demo1.xml");
//2、创建读取XML读取对象
SAXReader sr = new SAXReader();
//3、读取并得到文档对象
Document doc = sr.read(fis);
//4、通过文档获取根元素
Element root = doc.getRootElement();
//5、开始解析元素,获取主节点名称
System.out.println(root.getName());
//6、获取所有的子节点对象
List<Element> es = root.elements();
//遍历整个子节点
for (Element e:es) {
//获取节点的属性值 String attributeValue(String 属性名称);
System.out.println(e.attributeValue("id"));
//获取子节点的内容 String elementText(String 子节点名称)
System.out.println(e.elementText("name"));
System.out.println(e.elementText("info"));
}
//关闭流
fis.close();
}
}
解析网络XML
public class Demo2 {
public static void main(String[] args) throws IOException, DocumentException {
//1、获取输入流
String phone = "19980784807";
URL url = new URL("http://apis.juhe.cn/mobile/get?phone="+phone+"&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
//2、创建读取XML读取对象
SAXReader sr = new SAXReader();
//3、读取并得到文档对象
Document doc = sr.read(is);
//4、通过文档获取根元素
Element root = doc.getRootElement();
//5、判断读取是否成功
String code = root.elementText("resultcode");
if(code.equals("200")){
//code为200表示号码输入正确
Element result = root.element("result");
String province = result.elementText("province");
String city = result.elementText("city");
if(province.equals(city)){
System.out.println("该电话号码归属地为:"+city);
}else{
System.out.println("该电话号码归属地为:"+province+" "+city);
}
}else{
System.out.println("输入电话号码有误");
}
//关闭流
is.close();
}
}