package com.liantuo.tms.common.util; import java.io.StringReader; import java.io.StringWriter; import java.util.concurrent.ConcurrentHashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.transform.stream.StreamResult; /** * xml字符串和对象转换类 * */ public class XmlUtil { // 存放对类创建JAXBContext对象 private static ConcurrentHashMap<String, JAXBContext> jaxbcontextmap = new ConcurrentHashMap<String, JAXBContext>(); /** * 创建单例JAXBContext对象,并将对象放到ConcurrentHashMap中 * @param c Class * @return * @throws JAXBException */ public static JAXBContext getJAXBContext(Class<?> c) throws JAXBException { JAXBContext context = jaxbcontextmap.get(c.getName()); if (context != null) { return context; } else { context = JAXBContext.newInstance(c); jaxbcontextmap.put(c.getName(), context); return context; } } /** * 把xml配置转换成对象 * * @param xml * @param classObj * @return */ public static Object unmarshal(String xml, Class<?> classObj) { Object obj; try { JAXBContext jaxbContext = getJAXBContext(classObj); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); obj = unmarshaller.unmarshal(new StringReader(xml)); return obj; } catch (JAXBException e) { e.printStackTrace(); } return null; } /** * 把对象转换成xml配置 * * @param classObj * @param obj * @return */ public static String marshal(Class<?> classObj, Object obj) { String xmlStr = ""; try { JAXBContext jaxbContext = getJAXBContext(classObj); Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter out = new StringWriter(); marshaller.marshal(obj, new StreamResult(out)); xmlStr = out.toString(); } catch (JAXBException e) { e.printStackTrace(); } return xmlStr.toString(); } }

gan857569302 LV92020年6月23日
XiMenChuiBi LV22020年6月5日
筱进GG LV382019年8月3日
yzc2219 LV92019年6月24日
Mississippi21 LV22019年5月30日
重庆聚农汇 LV12019年4月2日
十小时 LV122018年7月11日
阿远远 LV82018年7月2日
myq_123 LV22017年11月12日
chenzp LV152017年10月29日

said_what LV32020年9月24日
jachyn LV42020年9月9日
gan857569302 LV92020年6月23日
XiMenChuiBi LV22020年6月5日
luohaipeng LV232019年12月3日
is_gary LV142019年8月18日
一页尘埃 LV72019年8月16日
筱进GG LV382019年8月3日
yaoyahui LV62019年7月15日
yzc2219 LV92019年6月24日