涉及:【正则表达式】
public static Map xml2map(String xml) {
Map map = new HashMap();
Pattern pattern = Pattern.compile("<(\\w+)>(<\\!\\[CDATA\\[([\\s\\S]+)\\]\\]>|[\\s\\S]+)<\\/\\1>");
Matcher matcher = pattern.matcher(xml);
if (!matcher.find()) {
log.warn(String.format("Parse failure(1) xml:%s", xml));
return map;
}
if (!"xml".equalsIgnoreCase(matcher.group(1))) {
log.warn(String.format("Parse failure(2) xml:%s", xml));
return map;
}
Matcher match = pattern.matcher(matcher.group(2));
while (match.find()) {
//这里考虑""是有效的,就不用StringUtils的isBlank或isEmpty
if (null == match.group(3)) {
map.put(match.group(1), match.group(2));
} else {
map.put(match.group(1), match.group(3));
}
}
return map;
}
欢迎吐槽交流