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(); } }

1358849392 LV21
2022年11月11日
Hachi6 LV13
2021年5月10日
503382513 LV10
2021年4月1日
tansuo阿郎 LV8
2021年2月27日
gan857569302 LV9
2020年6月23日
XiMenChuiBi LV2
2020年6月5日
低调人 LV38
2019年8月3日
yzc2219 LV9
2019年6月24日
Mississippi21 LV2
2019年5月30日
重庆聚农汇 LV1
2019年4月2日