标签:rate vat ++ cat XML object hash xml转json builder
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
public static String xmlToJSON(String xml,int jsonType) {
JSONObject obj = new JSONObject();
try {
InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
Map map=iterateElement(root);
obj.put(root.getName(),map);
return obj.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static Map iterateElement(Element root) {
List childrenList = root.getChildren();
Element element = null;
Map map = new HashMap();
List list = null;
for (int i = 0; i < childrenList.size(); i++) {
list = new ArrayList();
element = (Element) childrenList.get(i);
if(element.getChildren().size()>0){
if(root.getChildren(element.getName()).size()>1){
if (map.containsKey(element.getName())) {
list = (List) map.get(element.getName());
}
list.add(iterateElement(element));
map.put(element.getName(), list);
}else{
map.put(element.getName(), iterateElement(element));
}
}else {
if(root.getChildren(element.getName()).size()>1){
if (map.containsKey(element.getName())) {
list = (List) map.get(element.getName());
}
list.add(element.getTextTrim());
map.put(element.getName(), list);
}else{
map.put(element.getName(), element.getTextTrim());
}
}
}
return map;
}
xml转json
标签:rate vat ++ cat XML object hash xml转json builder
原文地址:https://www.cnblogs.com/bchange/p/9181998.html