XML回転JSON
5970 ワード
package com.Text;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
public class xmlJson {
/**
* xml
*
* @param xmlStr
* @return
* @throws DocumentException
*/
public static JSONObject xml(String xmlStr) throws DocumentException {
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject();
xmlToJson(doc.getRootElement(), json);
return json;
}
/**
* xml json
*
* @param element
* @param json
*/
public static void xmlToJson(Element element, JSONObject json) {
//
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List chdEl = element.elements();
if (chdEl.isEmpty() && !isEmpty(element.getText())) {// ,
json.put(element.getName(), element.getText());
}
for (Element e : chdEl) {//
if (!e.elements().isEmpty()) {//
JSONObject chdjson = new JSONObject();
xmlToJson(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
if (o instanceof JSONObject) {// , jsonArray
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 {//
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
}
}
public static boolean isEmpty(String str) {
if (str == null || str.trim().isEmpty() || "null".equals(str)) {
return true;
}
return false;
}
}