XMLUtil.java 20 KB

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