XMLUtil.java 20 KB

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