Dom4j解析第三方接口返回XML格式数据

本文介绍如何使用Dom4j库解析XML字符串,并提取关键属性值。通过具体示例展示了Dom4j的基本用法,包括创建SAXReader对象、读取XML内容、获取根元素及属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入Dom4j依赖
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
Dom4j解析
    public static void main(String[] args) {

        String xml = "<Response retCode=\"000\" scoreID=\"1920011\" score=\"848\" fraud=\"5\" />";
        InputStream is = null;
        try {
            SAXReader reader = new SAXReader();
            is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
            Document doc = reader.read(is);
            Element root = doc.getRootElement();
            
            String retCode = root.attributeValue("retCode");
            String scoreID = root.attributeValue("scoreID");
            String score = root.attributeValue("score");
            String fraud = root.attributeValue("fraud");
            
            System.out.println("retCode: " + retCode + " scoreID: " + scoreID + " score: " + score + " fraud: " + fraud);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

处理结果

retCode: 000 scoreID: 1920011 score: 848 fraud: 5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值