public static JSONObject xmlToFastJson(String xml){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
iterateNodes(root, jsonObject);
}catch (Exception e){
return jsonObject;
}
return jsonObject;
}
public static void iterateNodes(Element node, JSONObject json) {
String nodeName = node.getName();
if (json.containsKey(nodeName)) {
Object Object = json.get(nodeName);
JSONArray array;
if (Object instanceof JSONArray) {
array = (JSONArray) Object;
}
else {
array = new JSONArray();
array.add(Object);
}
List<Element> listElement = node.elements();
if (listElement.isEmpty()) {
String nodeValue = node.getTextTrim();
array.add(nodeValue);
json.put(nodeName, array);
return;
}
JSONObject newJson = new JSONObject();
for (Element e : listElement) {
iterateNodes(e, newJson);
}
array.add(newJson);
json.put(nodeName, array);
return;
}
List<Element> listElement = node.elements();
if (listElement.isEmpty()) {
String nodeValue = node.getTextTrim();
json.put(nodeName, nodeValue);
return;
}
JSONObject object = new JSONObject();
for (Element e : listElement) {
iterateNodes(e, object);
}
json.put(nodeName, object);
return;
}