Java解析XML字符串

在网上找了很多Java语言解析XML字符串的资料,很多内容写得很繁复,没有普适性,遂自己动手写了一个用Java解析XML的工具类。话不多说,直接看下面代码:

XML解析工具类:

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : chenfan
 * @className : XMLParse
 * @date : Created in 2021/3/29 13:59
 * @description : XML解析工具
 */

public class XMLParse {

    public static Map<String, Object> getValueByNode(String xml, List<String> nodes, String charsetName) throws DocumentException, UnsupportedEncodingException {
        Document document = new SAXReader().read(new ByteArrayInputStream(xml.getBytes(charsetName)));
        Map<String, Object> result = new HashMap();
        nodes.forEach(node -> {
            String xpath = "//" + node;
            Node singleNode = document.selectSingleNode(xpath);
            if(singleNode != null) {
                result.put(node, singleNode.getStringValue());
            }
        });
        return result;
    }
}

测试案例:

import com.chenfan.XMLParse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : chenfan
 * @className : TestXmlPrase
 * @date : Created in 2021/3/29 14:02
 * @description : 测试类
 */
public class TestXmlPrase {
    public static void main(String[] args) {
        String xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>\n" +
                     "<HouseVo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
                     "  <returnCode>100</returnCode>\n" +
                     "  <reason>获取成功!</reason>\n" +
                     "  <orderNo>ZK12345678</orderNo>\n" +
                     "  <totalAmount>2000000</totalAmount>\n" +
                     "  <payedAmount>0</payedAmount>\n" +
                     "  <oweAmount>0</oweAmount>\n" +
                     "  <name>张三</name>\n" +
                     "  <addr>测试用例</addr>\n" +
                     "</HouseVo>";

        Map<String, Object> map = new HashMap<>();
        try {
            List<String> nodes = new ArrayList<>();
            nodes.add("returnCode");
            nodes.add("reason");
            nodes.add("orderNo");
            nodes.add("totalAmount");
            nodes.add("payedAmount");
            nodes.add("oweAmount");
            nodes.add("name");
            nodes.add("addr");

            /*
             * 注意此处处理xml报文的坑:
             * xml报文encoding是utf-16,所以此处XML解析的charsetName须为utf-16
             * charsetName若跟xml报文encoding不一致,会报错:“前言中不允许有内容”
             */
            map = XMLParse.getValueByNode(xml, nodes, "utf-16");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("xml解析失败");
        }

        System.out.println("returnCode:" + map.get("returnCode"));
        System.out.println("reason:" + map.get("reason"));
        System.out.println("orderNo:" + map.get("orderNo"));
        System.out.println("totalAmount:" + map.get("totalAmount"));
        System.out.println("payedAmount:" + map.get("payedAmount"));
        System.out.println("oweAmount:" + map.get("oweAmount"));
        System.out.println("name:" + map.get("name"));
        System.out.println("addr:" + map.get("addr"));

    }
}

测试结果:

在这里插入图片描述

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值