XMLUtil.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. package com.yihu.wlyy.util;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonParser;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.dataformat.xml.XmlMapper;
  6. import net.sf.json.JSON;
  7. import net.sf.json.JSONArray;
  8. import net.sf.json.JSONObject;
  9. import net.sf.json.xml.XMLSerializer;
  10. import org.dom4j.*;
  11. import org.dom4j.io.OutputFormat;
  12. import org.dom4j.io.SAXReader;
  13. import org.dom4j.io.XMLWriter;
  14. import org.dom4j.tree.DefaultAttribute;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import org.springframework.util.StringUtils;
  18. import java.io.*;
  19. import java.lang.reflect.Field;
  20. import java.util.*;
  21. import java.util.regex.Matcher;
  22. import java.util.regex.Pattern;
  23. public class XMLUtil {
  24. private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);
  25. /**
  26. * 把xml字符串转换成 Document对象。
  27. *
  28. * @param xml 需要转换的xml字符串
  29. * @return 返回Document对象
  30. * @throws Exception 如果转换成Document对象异常的话抛出异常。
  31. */
  32. public static Document parseXml(String xml) throws Exception {
  33. try {
  34. return DocumentHelper.parseText(xml);
  35. } catch (DocumentException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. throw new Exception("传入的 xml 不是标准的xml字符串,请检查字符串是否合法。");
  39. }
  40. }
  41. /**
  42. * 转换成xml字符串
  43. *
  44. * @param xmlDoc 需要解析的xml对象
  45. * @throws Exception
  46. */
  47. public static String toXML_UTF_8(Document xmlDoc) throws Exception {
  48. return toXML(xmlDoc, "UTF-8", true);
  49. }
  50. /**
  51. * 转换成xml字符串
  52. *
  53. * @param xmlDoc 需要解析的xml对象
  54. * @throws Exception
  55. */
  56. public static String toXML_GBK(Document xmlDoc) throws Exception {
  57. return toXML(xmlDoc, "GBK", true);
  58. }
  59. /**
  60. * 转换成xml字符串
  61. *
  62. * @param xmlDoc 需要解析的xml对象
  63. * @param encoding 编码格式:UTF-8、GBK
  64. * @param iscom 是否为紧凑型格式
  65. * @return 修正完成后的xml字符串
  66. * @throws Exception
  67. */
  68. public static String toXML(Document xmlDoc, String encoding,
  69. boolean iscom) throws Exception {
  70. ByteArrayOutputStream byteRep = new ByteArrayOutputStream();
  71. OutputFormat format = null;
  72. if (iscom) {
  73. format = OutputFormat.createCompactFormat();// 紧凑型格式
  74. } else {
  75. format = OutputFormat.createPrettyPrint();// 缩减型格式
  76. }
  77. format.setEncoding(encoding);// 设置编码
  78. format.setTrimText(false);// 设置text中是否要删除其中多余的空格
  79. XMLWriter xw;
  80. try {
  81. xw = new XMLWriter(byteRep, format);
  82. xw.write(xmlDoc);
  83. } catch (UnsupportedEncodingException e) {
  84. // TODO Auto-generated catch block
  85. e.printStackTrace();
  86. throw new Exception("传入的编码格式错误,请传入正确的编码。");
  87. } catch (IOException e) {
  88. // TODO Auto-generated catch block
  89. e.printStackTrace();
  90. throw new Exception("文档转换成xml字符串时出错。" + xmlDoc.asXML());
  91. }
  92. return byteRep.toString();
  93. }
  94. /**
  95. * 对节点Element 添加节点。
  96. *
  97. * @param e 需要添加的节点
  98. * @param name 添加的节点的名称
  99. * @param value 添加的内容
  100. * <br/>
  101. * Demo:
  102. * < Root > aaa < /Root >
  103. * <br/>
  104. * call--> addChildElement(root, "A", "a");
  105. * <br/>
  106. * result--> < Root >< A >a< /A >< /Root >
  107. */
  108. public static void addElement(Element e, String name, Object value) {
  109. if (isBlank(value)) {
  110. e.addElement(name).addText("");
  111. } else {
  112. e.addElement(name).addText(value.toString());
  113. }
  114. }
  115. /**
  116. * 判断对象是否为空!(null,"", "null")
  117. *
  118. * @param value
  119. * @return
  120. */
  121. private static boolean isBlank(String value) {
  122. if (value == null || value.length() == 0) {
  123. return true;
  124. } else if (StringUtils.isEmpty(value)) {
  125. return true;
  126. } else {
  127. return false;
  128. }
  129. }
  130. /**
  131. * 判断对象是否非空!(null,"", "null")
  132. *
  133. * @param obj
  134. * @return
  135. */
  136. public static boolean isNotBlank(Object obj) {
  137. return !isBlank(obj);
  138. }
  139. /**
  140. * 判断对象是否为空!(null,"", "null")
  141. *
  142. * @param obj
  143. * @return
  144. */
  145. public static boolean isBlank(Object obj) {
  146. if (obj == null) {
  147. return true;
  148. }
  149. if (obj instanceof String) {
  150. return isBlank((String) obj);
  151. } else {
  152. return isBlank(obj.toString());
  153. }
  154. }
  155. public static void addElement(Element e, String name, Integer value) {
  156. Element current = e.addElement(name);
  157. if (value != null) {
  158. current.setText(Integer.toString(value));
  159. }
  160. }
  161. /**
  162. * 添加CDATA 类型节点
  163. *
  164. * @param e
  165. * @param name
  166. * @param value
  167. */
  168. public static void addCDATAElement(Element e, String name, String value) {
  169. Element current = e.addElement(name);
  170. if (value != null) {
  171. current.addCDATA(value.trim());
  172. }
  173. }
  174. /**
  175. * 添加CDATA 类型节点
  176. *
  177. * @param e
  178. * @param name
  179. * @param value
  180. */
  181. public static void addCDATAElement(Element e, String name, Integer value) {
  182. Element current = e.addElement(name);
  183. if (value != null) {
  184. current.addCDATA(value.toString());
  185. }
  186. }
  187. /**
  188. * 获取节点中的整数
  189. *
  190. * @throws Exception
  191. */
  192. public static int getInt(Element e, String name, boolean isMust) throws Exception {
  193. Element current = e.element(name);
  194. if (current == null || current.getText() == null || "".equals(current.getText().trim()) || current.getText().length() <= 0) {
  195. if (isMust) {
  196. throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
  197. }
  198. return 0;
  199. }
  200. Integer i = 0;
  201. try {
  202. i = Integer.parseInt(current.getTextTrim());
  203. } catch (NumberFormatException e1) {
  204. i = 0;
  205. if (isMust) {
  206. throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值不是整形。");
  207. }
  208. }
  209. return i;
  210. }
  211. /**
  212. * 获取节点中的字符串
  213. *
  214. * @throws Exception
  215. */
  216. public static String getString(Element e, String name, boolean isMust) throws Exception {
  217. return getString(e, name, isMust, null);
  218. }
  219. /**
  220. * 获取节点中的字符串
  221. *
  222. * @param e
  223. * @param name
  224. * @param isMust 是否必填 true 必填 false非必填
  225. * @param defVal 默认值
  226. * @return
  227. * @throws Exception
  228. */
  229. public static String getString(Element e, String name, boolean isMust, String defVal) throws Exception {
  230. Element current = e.element(name);
  231. if (current == null || current.getText() == null || StringUtils.isEmpty(current.getText().trim())) {
  232. if (isMust) {
  233. throw new Exception("在 $" + e.asXML() + "$中获取节点:" + name + " 的值为空。");
  234. }
  235. return defVal;
  236. }
  237. return current.getTextTrim();
  238. }
  239. public static String ElementStringValue(String str) {
  240. if (str != null) {
  241. return str;
  242. } else {
  243. return "";
  244. }
  245. }
  246. public static Integer ElementIntegerValue(Integer str) {
  247. if (str != null) {
  248. return str;
  249. } else {
  250. return 0;
  251. }
  252. }
  253. public static String ElementValue(String str) {
  254. if (str != null && !str.equalsIgnoreCase("null")) {
  255. return str;
  256. } else {
  257. return "";
  258. }
  259. }
  260. public static String xml2JSON(String xml) {
  261. if (StringUtils.isEmpty(xml)) {
  262. return "";
  263. } else {
  264. xml = xml.replace("\r","").replace("\n","").replace("\t","").replace("\f", "");
  265. Pattern p = Pattern.compile(">\\s*<");// 增加对应的标点
  266. Matcher m = p.matcher(xml);
  267. xml = m.replaceAll("><");
  268. XMLSerializer xmlSerializer = new XMLSerializer();
  269. xmlSerializer.setTrimSpaces(false);
  270. xmlSerializer.setSkipNamespaces(false);
  271. JSON read = xmlSerializer.read(xml);
  272. return read.toString();
  273. }
  274. }
  275. public static String xml2json(String xml){
  276. StringWriter w = new StringWriter();
  277. ObjectMapper objectMapper = new ObjectMapper();
  278. XmlMapper xmlMapper = new XmlMapper();
  279. JsonParser jp;
  280. try {
  281. jp = xmlMapper.getFactory().createParser(xml);
  282. JsonGenerator jg = objectMapper.getFactory().createGenerator(w);
  283. while (jp.nextToken() != null) {
  284. String name = jp.getParsingContext().getCurrentName();
  285. if ("".equals(name)){
  286. jp.overrideCurrentName("text");
  287. }
  288. jg.copyCurrentEvent(jp);
  289. }
  290. jp.close();
  291. jg.close();
  292. } catch (Exception e) {
  293. e.printStackTrace();
  294. }
  295. return w.toString();
  296. }
  297. public static String json2XML(String json) {
  298. if (StringUtils.isEmpty(json)) {
  299. return "";
  300. } else {
  301. XMLSerializer xmlSerializer = new XMLSerializer();
  302. JSONObject jobj = JSONObject.fromObject(json);
  303. String xmlStr = xmlSerializer.write(jobj);
  304. String xml = xmlStr.replace(
  305. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "").replace(
  306. "<o>", "").replace("</o>", "");
  307. return xml;
  308. }
  309. }
  310. public static String json2XML(String jsonStr, String rootName) {
  311. JSONObject json = JSONObject.fromObject(jsonStr);
  312. StringBuffer reqXml = new StringBuffer();
  313. reqXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><" + rootName + ">");
  314. reqXml.append(GetXml(json));
  315. reqXml.append("</" + rootName + ">");
  316. String rt = reqXml.toString();
  317. return rt;
  318. }
  319. public static String jsonToXml(String jsonStr) {
  320. JSONObject json = JSONObject.fromObject(jsonStr);
  321. StringBuffer reqXml = new StringBuffer();
  322. reqXml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  323. reqXml.append(GetXml(json));
  324. String rt = reqXml.toString();
  325. return rt;
  326. }
  327. private static String GetXml(JSONObject json) {
  328. StringBuffer sb = new StringBuffer();
  329. if (json != null && !json.isNullObject()) {
  330. Iterator<?> iter = json.keys();
  331. while (iter.hasNext()) {
  332. String key = (String) iter.next();
  333. if (json.get(key) instanceof JSONObject) {
  334. sb.append("<").append(key).append(">");
  335. sb.append(GetXml(json.getJSONObject(key)));
  336. sb.append("</").append(key).append(">");
  337. } else if (json.get(key) instanceof JSONArray) {
  338. JSONArray array = json.getJSONArray(key);
  339. if (array != null && array.size() > 0) {
  340. for (int i = 0; i < array.size(); i++) {
  341. sb.append("<").append(key).append(">");
  342. sb.append(GetXml(array.getJSONObject(i)));
  343. sb.append("</").append(key).append(">");
  344. }
  345. }
  346. } else {
  347. sb.append("<").append(key).append(">").append(json.getString(key)).append("</").append(key).append(">");
  348. }
  349. }
  350. }
  351. return sb.toString();
  352. }
  353. // public static void main(String[] args) throws Exception {
  354. //
  355. //// Document doc = parseXml("<Root></Root>");
  356. //// `` Element root = doc.getRootElement();
  357. //// addElement(root, "A", "阿萨德飞");
  358. //// addElement(root, "A", 2);
  359. //// System.out.println("添加子节点:\r\n"+toXML(doc, "GBK", true));
  360. //// addCDATAElement(root, "B", "所发生的");
  361. //// System.out.println("添加 CDATA 子节点:\r\n"+toXML(doc, "UTF-8", true));
  362. //
  363. // String xml = "<Resp><TransactionCode></TransactionCode><RespCode>10000</RespCode><RespMessage>医生查询信息成功</RespMessage><Data><DeptCode>286</DeptCode><DoctorName>陈久毅</DoctorName><Spec>在骨科方面有较高的造诣,率先于我科开展人工髋、膝关节置换手术,擅长人工髋、膝关节置换,关节外科,中西医结合治疗骨折、骨肿瘤、先天性畸形、各种软组织损伤,对四肢骨骨折闭合复位独树一帜。</Spec><DoctorTitle>主任医师</DoctorTitle><DoctorCode>164</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>田民</DoctorName><Spec>骨与关节疾病、创伤骨科、脊柱外科。</Spec><DoctorTitle>主任医师</DoctorTitle><DoctorCode>266</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>王松</DoctorName><Spec>善长运用AO技术、中西医结合治疗各种骨折;各种关节疾患、脊柱骨病的治疗;小儿骨科和关节镜微创技术,在创伤矫形、关节外科、脊柱外科有较深的认识并作出了一些成绩。</Spec><DoctorTitle>主任医师</DoctorTitle><DoctorCode>169</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>张开伟</DoctorName><Spec>擅长人工关节置换、关节镜及其它骨科微创手术。</Spec><DoctorTitle>主任医师</DoctorTitle><DoctorCode>174</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>祝乾清</DoctorName><Spec>擅长手法骨折复位、骨科微创手术。</Spec><DoctorTitle>主任医师</DoctorTitle><DoctorCode>168</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>方明智</DoctorName><Spec>骨与关节疾病、创伤骨科、脊柱外科。</Spec><DoctorTitle>副主任医师</DoctorTitle><DoctorCode>176</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>李贵华</DoctorName><Spec>创伤康复、颈肩腰腿痛、骨性关节炎及骨质疏松症的中西医治疗。</Spec><DoctorTitle>副主任医师</DoctorTitle><DoctorCode>172</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>李玉雄</DoctorName><Spec>在股骨头坏死、骨髓炎、骨结核、外伤性感染等病的中西医结合治疗颇具特色。</Spec><DoctorTitle>副主任医师</DoctorTitle><DoctorCode>171</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>沈俊</DoctorName><Spec>擅长于治疗各种创伤、颈椎病、股骨头缺血坏死、骨质疏松症、骨关节炎等骨科疾病以及小儿骨科领域的疾患。</Spec><DoctorTitle>副主任医师</DoctorTitle><DoctorCode>173</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data><Data><DeptCode>286</DeptCode><DoctorName>周建鸿</DoctorName><Spec>擅长脊柱关节疾病、颈椎前后路手术、腰椎间盘突出症、腰椎管狭窄以及脊柱肿瘤的手术治疗。</Spec><DoctorTitle>副主任医师</DoctorTitle><DoctorCode>4545</DoctorCode><DeptName>贵州省骨伤医院</DeptName></Data></Resp>";
  364. // System.out.println(formatXML(parseXml(xml)));
  365. // }
  366. public static String formatXML(Document doc) throws Exception {
  367. StringWriter out = null;
  368. try {
  369. OutputFormat formate = OutputFormat.createPrettyPrint();
  370. out = new StringWriter();
  371. XMLWriter writer = new XMLWriter(out, formate);
  372. writer.write(doc);
  373. } catch (IOException e) {
  374. e.printStackTrace();
  375. } finally {
  376. out.close();
  377. }
  378. return out.toString();
  379. }
  380. // ---------- map转XML--------------
  381. public static String map2xml(Map<String, String> dataMap) {
  382. synchronized (XMLUtil.class) {
  383. StringBuilder strBuilder = new StringBuilder();
  384. strBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  385. strBuilder.append("<QUERY_FORM>");
  386. Set<String> objSet = dataMap.keySet();
  387. for (Object key : objSet) {
  388. if (key == null) {
  389. continue;
  390. }
  391. strBuilder.append("<").append(key.toString()).append(">");
  392. Object value = dataMap.get(key);
  393. strBuilder.append(coverter(value));
  394. strBuilder.append("</").append(key.toString()).append(">");
  395. }
  396. strBuilder.append("</QUERY_FORM>");
  397. return strBuilder.toString();
  398. }
  399. }
  400. public static String coverter(Object[] objects) {
  401. StringBuilder strBuilder = new StringBuilder();
  402. for (Object obj : objects) {
  403. strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n");
  404. strBuilder.append(coverter(obj));
  405. strBuilder.append("</item>\n");
  406. }
  407. return strBuilder.toString();
  408. }
  409. public static String coverter(Collection<?> objects) {
  410. StringBuilder strBuilder = new StringBuilder();
  411. for (Object obj : objects) {
  412. strBuilder.append("<item className=").append(obj.getClass().getName()).append(">\n");
  413. strBuilder.append(coverter(obj));
  414. strBuilder.append("</item>\n");
  415. }
  416. return strBuilder.toString();
  417. }
  418. public static String coverter(Object object) {
  419. if (object instanceof Object[]) {
  420. return coverter((Object[]) object);
  421. }
  422. if (object instanceof Collection) {
  423. return coverter((Collection<?>) object);
  424. }
  425. StringBuilder strBuilder = new StringBuilder();
  426. if (isObject(object)) {
  427. Class<? extends Object> clz = object.getClass();
  428. Field[] fields = clz.getDeclaredFields();
  429. for (Field field : fields) {
  430. field.setAccessible(true);
  431. if (field == null) {
  432. continue;
  433. }
  434. String fieldName = field.getName();
  435. Object value = null;
  436. try {
  437. value = field.get(object);
  438. } catch (IllegalArgumentException e) {
  439. continue;
  440. } catch (IllegalAccessException e) {
  441. continue;
  442. }
  443. strBuilder.append("<").append(fieldName)
  444. .append(" className=\"").append(
  445. value.getClass().getName()).append("\">");
  446. if (isObject(value)) {
  447. strBuilder.append(coverter(value));
  448. } else if (value == null) {
  449. strBuilder.append("null");
  450. } else {
  451. strBuilder.append(value.toString() + "");
  452. }
  453. strBuilder.append("</").append(fieldName).append(">");
  454. }
  455. } else if (object == null) {
  456. strBuilder.append("null");
  457. } else {
  458. strBuilder.append(object.toString());
  459. }
  460. return strBuilder.toString();
  461. }
  462. private static boolean isObject(Object obj) {
  463. if (obj == null) {
  464. return false;
  465. }
  466. if (obj instanceof String) {
  467. return false;
  468. }
  469. if (obj instanceof Integer) {
  470. return false;
  471. }
  472. if (obj instanceof Double) {
  473. return false;
  474. }
  475. if (obj instanceof Float) {
  476. return false;
  477. }
  478. if (obj instanceof Byte) {
  479. return false;
  480. }
  481. if (obj instanceof Long) {
  482. return false;
  483. }
  484. if (obj instanceof Character) {
  485. return false;
  486. }
  487. if (obj instanceof Short) {
  488. return false;
  489. }
  490. if (obj instanceof Boolean) {
  491. return false;
  492. }
  493. return true;
  494. }
  495. // --------------------xml转map---------------
  496. public static Map xml2map(String xmlString) throws DocumentException {
  497. SAXReader reader = new SAXReader();
  498. InputStream in_nocode = new ByteArrayInputStream(xmlString.getBytes());
  499. Document doc = reader.read(in_nocode);
  500. Element rootElement = doc.getRootElement();
  501. Map<String, Object> map = new HashMap<String, Object>();
  502. ele2map(map, rootElement);
  503. System.out.println(map);
  504. // 到此xml2map完成,下面的代码是将map转成了json用来观察我们的xml2map转换的是否ok
  505. String string = net.sf.json.JSONObject.fromObject(map).toString();
  506. System.out.println(string);
  507. return map;
  508. }
  509. private static void ele2map(Map map, Element ele) {
  510. // 获得当前节点的子节点
  511. List<Element> elements = ele.elements();
  512. if (elements.size() == 0) {
  513. // 没有子节点说明当前节点是叶子节点,直接取值即可
  514. map.put(ele.getName(), ele.getText());
  515. } else if (elements.size() == 1) {
  516. // 只有一个子节点说明不用考虑list的情况,直接继续递归即可
  517. Map<String, Object> tempMap = new HashMap<String, Object>();
  518. ele2map(tempMap, elements.get(0));
  519. //设置标签属性
  520. setAttributes(tempMap,elements.get(0));
  521. if (tempMap.size()==1){
  522. map.put(ele.getName(), ele.getText());
  523. }else {
  524. map.put(ele.getName(), tempMap);
  525. }
  526. } else {
  527. // 多个子节点的话就得考虑list的情况了,比如多个子节点有节点名称相同的
  528. // 构造一个map用来去重
  529. Map<String, Object> tempMap = new HashMap<String, Object>();
  530. for (Element element : elements) {
  531. tempMap.put(element.getName(), null);
  532. }
  533. Set<String> keySet = tempMap.keySet();
  534. for (String string : keySet) {
  535. Namespace namespace = elements.get(0).getNamespace();
  536. List<Element> elements2 = ele.elements(new QName(string, namespace));
  537. // 如果同名的数目大于1则表示要构建list
  538. if (elements2.size() > 1) {
  539. List<Map> list = new ArrayList<Map>();
  540. for (Element element : elements2) {
  541. Map<String, Object> tempMap1 = new HashMap<String, Object>();
  542. ele2map(tempMap1, element);
  543. setAttributes(tempMap1,element);
  544. list.add(tempMap1);
  545. }
  546. map.put(string, list);
  547. } else {
  548. // 同名的数量不大于1则直接递归去
  549. Map<String, Object> tempMap1 = new HashMap<String, Object>();
  550. ele2map(tempMap1, elements2.get(0));
  551. setAttributes(tempMap1,elements2.get(0));
  552. if (tempMap1.containsKey(string)) {
  553. map.put(string, tempMap1.get(string));
  554. }else {
  555. map.put(string, tempMap1);
  556. }
  557. }
  558. }
  559. }
  560. }
  561. /**
  562. *
  563. * 设置属性值(xml转map)
  564. * @param map
  565. * @param element
  566. */
  567. public static void setAttributes(Map map,Element element){
  568. List list = element.attributes();
  569. Map<String,Object> attrMap = null;
  570. DefaultAttribute e = null;
  571. if (!list.isEmpty()) {
  572. attrMap = new HashMap<>();
  573. for (int i = 0; i < list.size(); i++) {
  574. e = (DefaultAttribute) list.get(i);
  575. attrMap.put(e.getName(),e.getText());
  576. }
  577. attrMap.put("text",element.getText());
  578. }
  579. if (attrMap!=null && !attrMap.isEmpty()){
  580. map.put(element.getName(),attrMap);
  581. }
  582. }
  583. public static Map xmltoMap(String xml) {
  584. if (!StringUtils.isEmpty(xml)) {
  585. try {
  586. Map map = new HashMap();
  587. Document document = DocumentHelper.parseText(xml);
  588. Element nodeElement = document.getRootElement();
  589. List node = nodeElement.elements();
  590. for (Iterator it = node.iterator(); it.hasNext(); ) {
  591. Element elm = (Element) it.next();
  592. map.put(elm.getName(), elm.getText());
  593. elm = null;
  594. }
  595. node = null;
  596. nodeElement = null;
  597. document = null;
  598. return map;
  599. } catch (Exception e) {
  600. e.printStackTrace();
  601. }
  602. }
  603. return null;
  604. }
  605. public static List xmltoList(String xml) {
  606. if (!StringUtils.isEmpty(xml)) {
  607. try {
  608. List<Map> list = new ArrayList<Map>();
  609. Document document = DocumentHelper.parseText(xml);
  610. Element nodesElement = document.getRootElement();
  611. List nodes = nodesElement.elements();
  612. for (Iterator its = nodes.iterator(); its.hasNext(); ) {
  613. Element nodeElement = (Element) its.next();
  614. Map map = xmltoMap(nodeElement.asXML());
  615. list.add(map);
  616. map = null;
  617. }
  618. nodes = null;
  619. nodesElement = null;
  620. document = null;
  621. return list;
  622. } catch (Exception e) {
  623. e.printStackTrace();
  624. }
  625. }
  626. return null;
  627. }
  628. /* ============================== 以下暂时添加,后面可删除 ========================================= */
  629. // public static String maptoXml(Map map) {
  630. // Document document = DocumentHelper.createDocument();
  631. // Element nodeElement = document.addElement("node");
  632. // for (Object obj : map.keySet()) {
  633. // Element keyElement = nodeElement.addElement("key");
  634. // keyElement.addAttribute("label", String.valueOf(obj));
  635. // keyElement.setText(String.valueOf(map.get(obj)));
  636. // }
  637. // return doc2String(document);
  638. // }
  639. //
  640. // public static String listtoXml(List list) throws Exception {
  641. // Document document = DocumentHelper.createDocument();
  642. // Element nodesElement = document.addElement("nodes");
  643. // int i = 0;
  644. // for (Object o : list) {
  645. // Element nodeElement = nodesElement.addElement("node");
  646. // if (o instanceof Map) {
  647. // for (Object obj : ((Map) o).keySet()) {
  648. // Element keyElement = nodeElement.addElement("key");
  649. // keyElement.addAttribute("label", String.valueOf(obj));
  650. // keyElement.setText(String.valueOf(((Map) o).get(obj)));
  651. // }
  652. // } else {
  653. // Element keyElement = nodeElement.addElement("key");
  654. // keyElement.addAttribute("label", String.valueOf(i));
  655. // keyElement.setText(String.valueOf(o));
  656. // }
  657. // i++;
  658. // }
  659. // return doc2String(document);
  660. // }
  661. //
  662. // public static String doc2String(Document document) {
  663. // String s = "";
  664. // try {
  665. // // 使用输出流来进行转化
  666. // ByteArrayOutputStream out = new ByteArrayOutputStream();
  667. // // 使用UTF-8编码
  668. // OutputFormat format = new OutputFormat(" ", true, "UTF-8");
  669. // XMLWriter writer = new XMLWriter(out, format);
  670. // writer.write(document);
  671. // s = out.toString("UTF-8");
  672. // } catch (Exception ex) {
  673. // ex.printStackTrace();
  674. // }
  675. // return s;
  676. // }
  677. }