XML

解析本地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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值