XmlUtils.java 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. package com.kmall.admin.cuspay.util;
  2. import org.dom4j.Attribute;
  3. import org.dom4j.Document;
  4. import org.dom4j.Element;
  5. import org.xml.sax.Attributes;
  6. import org.xml.sax.InputSource;
  7. import org.xml.sax.SAXException;
  8. import org.xml.sax.XMLReader;
  9. import org.xml.sax.helpers.XMLFilterImpl;
  10. import javax.xml.bind.JAXBContext;
  11. import javax.xml.bind.Marshaller;
  12. import javax.xml.bind.Unmarshaller;
  13. import javax.xml.parsers.SAXParserFactory;
  14. import javax.xml.transform.Source;
  15. import javax.xml.transform.sax.SAXSource;
  16. import java.io.File;
  17. import java.io.StringReader;
  18. import java.io.StringWriter;
  19. import java.util.*;
  20. /**
  21. * XML处理类
  22. *
  23. * @author Scott Chen
  24. * @date 2016/11/15
  25. */
  26. public class XmlUtils {
  27. public static String toXML(Object obj, boolean format) throws Exception {
  28. try {
  29. JAXBContext context = JAXBContext.newInstance(obj.getClass());
  30. Marshaller marshaller = context.createMarshaller();
  31. //编码格式
  32. marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  33. // 是否格式化生成的xml串
  34. if (format) {
  35. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  36. }else{
  37. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
  38. }
  39. // 是否省略xm头声明信息
  40. marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
  41. StringWriter writer = new StringWriter();
  42. marshaller.marshal(obj, writer);
  43. return writer.toString();
  44. } catch (Exception e) {
  45. throw new RuntimeException(e);
  46. }
  47. }
  48. public static String toXMLInFile(Object obj, String filePath, boolean format) throws Exception {
  49. try {
  50. JAXBContext context = JAXBContext.newInstance(obj.getClass());
  51. Marshaller marshaller = context.createMarshaller();
  52. //编码格式
  53. marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
  54. // 是否格式化生成的xml串
  55. if (format) {
  56. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
  57. }else{
  58. marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
  59. }
  60. // 是否省略xm头声明信息
  61. marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
  62. File file = new File(filePath);
  63. marshaller.marshal(obj, file);
  64. StringWriter writer = new StringWriter();
  65. marshaller.marshal(obj, writer);
  66. return writer.toString();
  67. } catch (Exception e) {
  68. throw new RuntimeException(e);
  69. }
  70. }
  71. @SuppressWarnings("unchecked")
  72. public static <T> T fromXML(String xmlStr, Class<T> valueType, boolean ignoreNs) throws Exception {
  73. try {
  74. JAXBContext context = JAXBContext.newInstance(valueType);
  75. Unmarshaller unmarshaller = context.createUnmarshaller();
  76. StringReader reader = new StringReader(xmlStr);
  77. //解析时,是否忽略命名空间
  78. if (ignoreNs) {
  79. /**
  80. * 忽略命名空间
  81. * 在序列化和反序列化时通过XMLFilterImpl的匿名实现类实现命名空间及xml节点名称的控制
  82. */
  83. SAXParserFactory sax = SAXParserFactory.newInstance();
  84. //false:忽略命名空间
  85. sax.setNamespaceAware(false);
  86. XMLReader xmlReader = sax.newSAXParser().getXMLReader();
  87. XMLFilterImpl nsfFilter = new XMLFilterImpl() {
  88. private boolean ignoreNamespace = false;
  89. @Override
  90. public void startDocument() throws SAXException {
  91. super.startDocument();
  92. }
  93. @Override
  94. public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
  95. if (this.ignoreNamespace){
  96. uri = "";
  97. }
  98. super.startElement(uri, localName, qName, atts);
  99. }
  100. @Override
  101. public void endElement(String uri, String localName, String qName) throws SAXException {
  102. if (this.ignoreNamespace){
  103. uri = "";
  104. }
  105. super.endElement(uri, localName, localName);
  106. }
  107. @Override
  108. public void startPrefixMapping(String prefix, String url) throws SAXException {
  109. if (!this.ignoreNamespace){
  110. super.startPrefixMapping("", url);
  111. }
  112. }
  113. };
  114. nsfFilter.setParent(xmlReader);
  115. Source source = new SAXSource(xmlReader, new InputSource(reader));
  116. return (T) unmarshaller.unmarshal(source);
  117. }
  118. return (T) unmarshaller.unmarshal(reader);
  119. } catch (Exception e) {
  120. throw new RuntimeException(e);
  121. }
  122. }
  123. public static String map2Xml(Map<String, String> map) {
  124. StringBuffer sb = new StringBuffer();
  125. sb.append("<xml>");
  126. Set es = map.entrySet();
  127. Iterator it = es.iterator();
  128. while(it.hasNext()) {
  129. Map.Entry entry = (Map.Entry)it.next();
  130. String k = (String)entry.getKey();
  131. String v = (String)entry.getValue();
  132. //注意,有一些值要用![CDATA[value]]来表示
  133. // if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
  134. // sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
  135. // continue;
  136. // }else {
  137. sb.append("<"+k+">"+v+"</"+k+">");
  138. // }
  139. }
  140. sb.append("</xml>");
  141. return sb.toString();
  142. }
  143. public static Map<String, Object> Dom2Map(Document doc) {
  144. Map<String, Object> map = new HashMap<>();
  145. if (doc == null)
  146. return map;
  147. Element root = doc.getRootElement();
  148. for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext(); ) {
  149. Element e = iterator.next();
  150. List list = e.elements();
  151. if (list.size() > 0) {
  152. map.put(e.getName(), Dom2Map(e));
  153. continue;
  154. }
  155. map.put(e.getName(), e.getText());
  156. }
  157. return map;
  158. }
  159. private static Map Dom2Map(Element e) {
  160. Map<Object, Object> map = new HashMap<>();
  161. List<Element> list = e.elements();
  162. if (list.size() > 0) {
  163. for (int i = 0; i < list.size(); i++) {
  164. Element iter = list.get(i);
  165. List<Object> mapList = new ArrayList();
  166. String iterValue = iter.getName();
  167. if (iter.attributes().size() != 0) {
  168. Attribute attribute = iter.attribute(0);
  169. iterValue = attribute.getValue();
  170. }
  171. if (iter.elements().size() > 0) {
  172. Map m = Dom2Map(iter);
  173. if (map.get(iterValue) != null) {
  174. Object obj = map.get(iterValue);
  175. if (!obj.getClass().getName().equals("java.util.ArrayList")) {
  176. mapList = new ArrayList();
  177. mapList.add(obj);
  178. mapList.add(m);
  179. }
  180. if (obj.getClass().getName().equals("java.util.ArrayList")) {
  181. mapList = (List<Object>)obj;
  182. mapList.add(m);
  183. }
  184. map.put(iterValue, mapList);
  185. } else {
  186. map.put(iterValue, m);
  187. }
  188. } else if (map.get(iterValue) != null) {
  189. Object obj = map.get(iterValue);
  190. if (!obj.getClass().getName().equals("java.util.ArrayList")) {
  191. mapList = new ArrayList();
  192. mapList.add(obj);
  193. mapList.add(iter.getText());
  194. }
  195. if (obj.getClass().getName().equals("java.util.ArrayList")) {
  196. mapList = (List<Object>)obj;
  197. mapList.add(iter.getText());
  198. }
  199. map.put(iterValue, mapList);
  200. } else {
  201. map.put(iterValue, iter.getText());
  202. }
  203. }
  204. } else {
  205. map.put(e.getName(), e.getText());
  206. }
  207. return map;
  208. }
  209. }