使用Marshaller 将Java对象转化为XML格式
-
对象转xml内容
①工具类public static String convertObjectToXml(Object obj) throws Exception { StringWriter writer = new StringWriter(); // 创建 JAXBContext 和 Marshaller JAXBContext context = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = context.createMarshaller(); // 设置 Marshaller 属性 // 指定是否使用换行和缩排对已编组 XML 数据进行格式化的属性名称 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 指定是否带有xml报文头 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 将 Java 对象转换成 XML 标签 marshaller.marshal(obj, writer); return writer.toString(