在网上找了很多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"));}
}