大家好,又见面了,我是你们的朋友全栈君。
在网上找了很多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"));
}
}
测试结果:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/135977.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...