private static JSONObject xml2Json(String xmlStr) throws DocumentException {
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject();
dom4j2Json(doc.getRootElement(), json);
return json;
}
private static void dom4j2Json(Element element, JSONObject json) {
List<Element> chdEl = element.elements();
chdEl.forEach(e -> {
if (!e.elements().isEmpty()) {
JSONObject chdjson = new JSONObject();
dom4j2Json(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
} else {
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
});
}
xml转JSON方法
最新推荐文章于 2024-09-08 11:09:43 发布