package com.fzzy.push.gd2020; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import java.io.*; import java.nio.charset.Charset; import java.util.Map; public class JaxbUtil { /** * JavaBean装换成xml * 默认编码UTF-8 * * @param obj * @return */ public static String converTomXml(Object obj) { return converToXml(obj, "UTF-8"); } /** * JavaBean装换成xml * * @param obj * @param encoding * @return */ private static String converToXml(Object obj, String encoding) { String result = null; try { JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding); StringWriter writer = new StringWriter(); marshaller.marshal(obj, writer); result = writer.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } /** * xml装换成JavaBean * * @param xml * @param c * @return */ @SuppressWarnings("unchecked") public static T converyToJavaBean(String xml, Class c) { if(xml == null || xml.equals("")) return null; T t = null; StringReader reader = null; try { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); reader = new StringReader(xml); t = (T) unmarshaller.unmarshal(reader); } catch (Exception e) { } finally { if (reader != null) reader.close(); } return t; } /** * xml转换成JavaBean * * @param xml * @param c * @return */ @SuppressWarnings("unchecked") public static T convertToJava(String xml, Class c) { if (xml == null || xml.equals("")) return null; T t = null; StringReader reader = null; try { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); reader = new StringReader(xml); SAXParserFactory sax = SAXParserFactory.newInstance(); sax.setNamespaceAware(false);//主要代码 XMLReader xmlReader = sax.newSAXParser().getXMLReader(); Source source = new SAXSource(xmlReader, new InputSource(reader)); t = (T) unmarshaller.unmarshal(source); } catch (Exception e) { } finally { if (reader != null) reader.close(); } return t; } /** * (多层)map转换为xml格式字符串 * * @param map 需要转换为xml的map * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入 * @return xml字符串 * @throws UnsupportedEncodingException */ public static String multilayerMapToXml(Map map, boolean isCDATA) throws UnsupportedEncodingException { String parentName = "response"; Document doc = DocumentHelper.createDocument(); doc.addElement(parentName); String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCDATA); return formatXML(xml); } /** * multilayerMapToXml核心方法,递归调用 * * @param element 节点元素 * @param parentName 根元素属性名 * @param map 需要转换为xml的map * @param isCDATA 是否加入CDATA标识符 true:加入 false:不加入 * @return xml字符串 */ @SuppressWarnings("unchecked") private static String recursionMapToXml(Element element, String parentName, Map map, boolean isCDATA) { Element xmlElement = element.addElement(parentName); map.keySet().forEach(key -> { Object obj = map.get(key); if (obj instanceof Map) { recursionMapToXml(xmlElement, key, (Map) obj, isCDATA); } else { String value = obj == null ? "" : obj.toString(); if (isCDATA) { xmlElement.addElement(key).addCDATA(value); } else { xmlElement.addElement(key).addText(value); } } }); return xmlElement.asXML(); } /** * 格式化xml,显示为容易看的XML格式 * * @param xml 需要格式化的xml字符串 * @return */ public static String formatXML(String xml) { String requestXML = null; try { // 拿取解析器 SAXReader reader = new SAXReader(); Document document = reader.read(new StringReader(xml)); if (null != document) { StringWriter stringWriter = new StringWriter(); // 格式化,每一级前的空格 OutputFormat format = new OutputFormat(" ", true); // xml声明与内容是否添加空行 format.setNewLineAfterDeclaration(false); // 是否设置xml声明头部 format.setSuppressDeclaration(false); // 是否分行 format.setNewlines(true); XMLWriter writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); writer.close(); requestXML = stringWriter.getBuffer().toString(); } return requestXML; } catch (Exception e) { e.printStackTrace(); return null; } } /** * @param xmlStr * @param c * @return */ public static T xml2Object(String xmlStr, Class c) { try { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new InputStreamReader( new ByteArrayInputStream(xmlStr.getBytes()), Charset.forName("UTF-8"))); return t; } catch (JAXBException e) { e.printStackTrace(); return null; } } /** * java对象转换为xml文件 * * @param model java对象.Class * @return xml文件的String * @throws Exception */ public static String bean2Xml(Object obj, Class model) throws Exception { JAXBContext jaxbContext = JAXBContext.newInstance(model); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 设置编码字符集 // marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出,有分行和缩进 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // marshaller.setProperty("com.sun.xml.bind.xmlHeaders", // ""); ByteArrayOutputStream baos = new ByteArrayOutputStream(); marshaller.marshal(obj, baos); String xmlObj = new String(baos.toByteArray(), "UTF-8"); // 生成 return xmlObj; } /** * json * String转换为xml文件 * @param json * @return xml文件的 String * @throws Exception */ // public static String json2Xml(String json){ // String xml = ""; // try { // org.json.JSONObject json1 = new org.json.JSONObject(json); // xml += XML.toString(json1); // xml += ""; // }catch (Exception ex){ // ex.getStackTrace(); // } // return xml; // // } }