Java对象XML

来源:互联网 发布:智巢网络 编辑:程序博客网 时间:2024/05/25 23:58
private String beanToStringXml(Object obj) {
String xmlStr = null;
if (obj == null) {
return "";
}
try {
JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
marshaller.marshal(obj, sw);
xmlStr = sw.toString();


} catch (Exception e) {
throw new DataFormatException("obj:" + obj + ",转xml异常", e);
}
return xmlStr;
}