1、xml格式报文
String rtnMsgXML = "<?xml version=\"1.0\" encoding='UTF-8'?>\n" +
"<DBSET RESULT=\"1\">\n" +
"<R>\n" +
"<C N=\"rtnMsg\">短信发送失败</C>\n" +
"<C N=\"rtnCode\">1</C>\n" +
"</R>\n" +
"</DBSET>";
2、解析报文核心方法
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 = "//" + "R" + "//" + "C" + "[@N='"+node+"']";
Node singleNode = document.selectSingleNode(xpath);
if(singleNode != null) {
result.put(node, singleNode.getStringValue());
}
});
return result;
}
3、调用xml报文解析方法完成解析
List<String> nodes = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
nodes.add("rtnMsg");
nodes.add("rtnCode");
map1 = getValueByNode(rtnMsgXML, nodes, "UTF-8");
注:map1返回格式
{"rtnMsg":"短信发送失败","rtnCode":"1"}
4、最终代码
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public static void main(String[] args) {
String rtnMsgXML = "<?xml version=\"1.0\" encoding='UTF-8'?>\n" +
"<DBSET RESULT=\"1\">\n" +
"<R>\n" +
"<C N=\"rtnMsg\"></C>\n" +
"<C N=\"rtnCode\">0</C>\n" +
"</R>\n" +
"</DBSET>";
List<String> nodes = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
nodes.add("rtnMsg");
nodes.add("rtnCode");
map1 = getValueByNode(rtnMsgXML, nodes, "UTF-8");
}
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
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;
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 = "//" + "R" + "//" + "C" + "[@N='"+node+"']";
Node singleNode = document.selectSingleNode(xpath);
if(singleNode != null) {
result.put(node, singleNode.getStringValue());
}
});
return result;
}