java 进行xml文档解析
程序员文章站
2022-03-09 08:13:24
这份是对于postman请求时候,进行对于报文解析图一为报文发送的内容private Map getXml(HttpServletRequest request){ try { //初始化map Map map = new HashMap<>(); //获取request stream InputStream inputStream...
这份是对于postman请求时候,进行对于报文解析
图一为报文发送的内容
引入相关依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
调用这个方法后,所有的尖括号的值都已经存在,直接使用map.get 获取对应的key即可获取相关的value,进行封装对象操作:
private Map<String, String> getXml(HttpServletRequest request){
//初始化map
Map<String, String> map = new HashMap<>();
try {
//获取request stream
InputStream inputStream = request.getInputStream();
//解析xml
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
//获取head和body的xml
List<Element> elementList = root.elements();
for (Element e : elementList)
map.put(e.getName(), e.getText());
//获取head的元素
Element head = elementList.get(0);
List<Element> headList = head.elements();
for (Element e : headList)
map.put(e.getName(), e.getText());
//获取body的元素在进行二次清洗
Document bodydoc = DocumentHelper.parseText(StringEscapeUtils.unescapeXml(map.get("body")));
Element body = bodydoc.getRootElement();
List<Element> bodyList = body.elements();
for (Element e : bodyList)
map.put(e.getName(), e.getText());
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
return map;
}
获取所有的map的值
public void postUserMsgText(HttpServletRequest request){
Map<String, String> map = getXml(request);
for (String key : map.keySet()){
String s = map.get(key);
System.out.println(key + " : --> "+s);
}
}
本文地址:https://blog.csdn.net/weixin_46845168/article/details/110852548