首页 > 技术文章 > xml bean

yqlwl66 2019-09-06 11:36 原文

/**
* Bean to Xml *

* @date 2019/8/1 13:28
*/
private String beanToXml(Object obj) {
StringWriter sw = new StringWriter();
try {
//利用jdk中自带的转换类实现
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
//格式化xml输出的格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
//去掉生成xml的默认报文头
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//将对象转换成输出流形式的xml
marshaller.marshal(obj, sw);
} catch (JAXBException e) {
log.error("JAXB序化异常:" + e.getMessage(), e);
throw new ApiException(IbeExceptionEnum.JAXB_MARSHALLER_ERROR);
}
return sw.toString();
}

/**
* XML转Bean
* <p>
*
* @param body XML内容
* @param dataClass 数据类型
* @date 2019/7/30 16:37
*/
private <T> T xmlToBean(String body, Class<T> dataClass) throws ApiException {
if (StrUtil.isEmpty(body)) {
return null;
}
T data;
try {
JAXBContext context = JAXBContext.newInstance(dataClass);
Unmarshaller unmarshaller = context.createUnmarshaller();
//解析忽略命名空间
SAXParserFactory sax = SAXParserFactory.newInstance();
sax.setNamespaceAware(false);
XMLReader xmlReader = sax.newSAXParser().getXMLReader();
Source source = new SAXSource(xmlReader, new InputSource(new StringReader(body)));
// 反序列化
data = (T) unmarshaller.unmarshal(source);
} catch (Exception e) {
log.error("JAXB反序化异常:" + e.getMessage(), e);
throw new ApiException(IbeExceptionEnum.JAXB_UNMARSHALLER_ERROR);
}
return data;
}

推荐阅读