XMLUtil.java 26 KB

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