java利用dom4j将xml字符串转换为json
1 import java.util.HashMap; 2 import java.util.LinkedList; 3 import java.util.List; 4 import java.util.Map; 5 6 import org.dom4j.Document; 7 import org.dom4j.DocumentHelper; 8 import org.dom4j.Element; 9 10 import net.sf.json.JSONObject; 11 12 public class Xml2JsonUtil { 13 14 15 /** 16 * 转换一个xml格式的字符串到json格式 17 * 18 * @param xml 19 * xml格式的字符串 20 * @return 成功返回json 格式的字符串;失败反回null 21 */ 22 @SuppressWarnings("unchecked") 23 public static String xml2JSON(String xml) { 24 JSONObject obj = new JSONObject(); 25 try { 26 Document doc = DocumentHelper.parseText(xml); 27 Element root = doc.getRootElement(); 28 obj.put(root.getName(), iterateElement(root)); 29 return obj.toString(); 30 } catch (Exception e) { 31 e.printStackTrace(); 32 return null; 33 } 34 } 35 36 /** 37 * 一个迭代方法 38 * 39 * @param element 40 * @return java.util.Map 实例 41 */ 42 @SuppressWarnings("unchecked") 43 private static Map iterateElement(Element element) { 44 List jiedian = element.elements(); 45 Element et = null; 46 Map obj = new HashMap(); 47 Object temp; 48 List list = null; 49 for (int i = 0; i < jiedian.size(); i++) { 50 list = new LinkedList(); 51 et = (Element) jiedian.get(i); 52 if (et.getTextTrim().equals("")) { 53 if (et.elements().size() == 0) 54 continue; 55 if (obj.containsKey(et.getName())) { 56 temp = obj.get(et.getName()); 57 if(temp instanceof List){ 58 list = (List)temp; 59 list.add(iterateElement(et)); 60 }else if(temp instanceof Map){ 61 list.add((HashMap)temp); 62 list.add(iterateElement(et)); 63 }else{ 64 list.add((String)temp); 65 list.add(iterateElement(et)); 66 } 67 obj.put(et.getName(), list); 68 }else{ 69 obj.put(et.getName(), iterateElement(et)); 70 } 71 } else { 72 if (obj.containsKey(et.getName())) { 73 temp = obj.get(et.getName()); 74 if(temp instanceof List){ 75 list = (List)temp; 76 list.add(et.getTextTrim()); 77 }else if(temp instanceof Map){ 78 list.add((HashMap)temp); 79 list.add(iterateElement(et)); 80 }else{ 81 list.add((String)temp); 82 list.add(et.getTextTrim()); 83 } 84 obj.put(et.getName(), list); 85 }else{ 86 obj.put(et.getName(), et.getTextTrim()); 87 } 88 89 } 90 91 } 92 return obj; 93 } 94 95 // 测试 96 public static void main(String[] args) { 97 String xmlStr = "<getOmElement>" + 98 "<HEADER>" + 99 "<SOURCEID>MDM</SOURCEID>" + 100 "<SOURCEID>MDM</SOURCEID>" + 101 "<myChild/>"+ 102 "<DESTINATIONID>DAXT</DESTINATIONID>" + 103 "<SIZE>1</SIZE>" + 104 "<TYPE>ADD</TYPE>" + 105 "<BO>ORG</BO>" + 106 "<CHECK>"+ 107 "checkCode" 108 +"</CHECK>"+ 109 "</HEADER>" + 110 "<REQUEST>" + 111 "<DATAROW>" + 112 "<ORGUUID>460c5239-13f662e8f67-2f1936027f000a1d675dd1399911234</ORGUUID>" + 113 "</DATAROW>" + 114 "<DATAROW>" + 115 "<ORGUUID>460c5239-13f662e8f67-2f1936027f000a1d675dd139991369c4</ORGUUID>" + 116 "</DATAROW>" + 117 "</REQUEST>" + 118 "</getOmElement>"; 119 120 System.out.println(Xml2JsonUtil.xml2JSON(xmlStr)); 121 } 122 }