public static void xmlToJSON(Element element, JSONObject json) throwsJSONException {
var elementAttributes =element.attributes();
var elementText=element.getText();
List childElements =element.elements();for(Object Attribute : elementAttributes) {
Attribute attr=(Attribute) Attribute;if (!isEmpty(attr.getValue())) {
json.put("@" +attr.getName(), attr.getValue());
}
}if (!isEmpty(elementText)) {if(childElements.isEmpty()) {
json.put(element.getName(), element.getText());
}else{
json.put("#text", element.getText());
}
}for(Element childElement: childElements){
JSONObject childJSON= newJSONObject();
xmlToJSON(childElement, childJSON);
Object childObject=json.get(childElement.getName());if (childObject != null) {
JSONArray jsona= null;if (childObject instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
JSONObject jsono =(JSONObject) childObject;
json.remove(childElement.getName());
jsona= newJSONArray();
jsona.add(jsono);
jsona.add(childJSON);
}if (childObject instanceofJSONArray) {
jsona=(JSONArray) childObject;
jsona.add(childJSON);
}
json.put(childElement.getName(), jsona);
}else{if (!childJSON.isEmpty()) {
json.put(childElement.getName(), childJSON);
}
}
}
}