public void xmlToJSON(Element element, JSONObject json) throws JSONException { var elementAttributes = element.attributes(); var elementText = element.getText(); List<Element> childElements = element.elements(); for (Object Attribute : elementAttributes) { Attribute attr = (Attribute) Attribute; if (!isEmpty(attr.getValue())) { json.put("@" + attr.getName(), attr.getValue()); } } if (!isEmpty(elementText)) { json.put("#text", element.getText()); } for (Element childElement : childElements) { JSONObject childJSON = new JSONObject(); 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 = new JSONArray(); jsona.add(jsono); jsona.add(childJSON); } if (childObject instanceof JSONArray) { jsona = (JSONArray) childObject; jsona.add(childJSON); } json.put(childElement.getName(), jsona); } else { if (!childJSON.isEmpty()) { json.put(childElement.getName(), childJSON); } } } }
啥也不想说了. 上一个版本叫我覆盖掉了. . .
凑合看吧