Map<String, Object> map = new HashMap<>();
try {
List<String> nodes = new ArrayList<>();
nodes.add("ns2:stateDesc");
nodes.add("ns2:state");
map = getValueByNode(execute.body(), nodes, "utf-8");
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
/**
* 解析xml字符串
*/
public Map<String, Object> getValueByNode(String xml, List<String> nodes, String charsetName) throws DocumentException, UnsupportedEncodingException {
SAXReader saxReader = new SAXReader();
Map<String, String> nameMap = new HashMap<>();
nameMap.put("ns2", "http://vo.intf.all.smpin.tydic.com");
saxReader.getDocumentFactory().setXPathNamespaceURIs(nameMap);
Document document = 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;
}
dom4j+xpath解析xml文件
最新推荐文章于 2023-11-20 09:38:56 发布