如何将JAXB Marshaller生成的XML转为字符串并设置到响应对象?
解决方法:将JAXB Marshaller生成的XML转为字符串
嘿,这个需求太常见了!你只需要把Marshaller的输出目标从System.out换成StringWriter就能轻松拿到XML字符串,具体修改步骤很直观:
首先要导入java.io.StringWriter类,然后在try代码块里做这几步调整:
- 创建一个
StringWriter实例,用来捕获Marshaller输出的XML内容 - 把这个
StringWriter传给jaxbMarshaller.marshal()方法,替代原来的System.out - 调用
StringWriter的toString()方法获取完整的XML字符串,再设置到你的响应对象中
修改后的完整代码如下:
public StampaModuloPrivacyResponse generaXmlALC(StampaModuloPrivacyRequest input) { final StampaModuloPrivacyResponse stampaModuloPrivacyResponse = new StampaModuloPrivacyResponse(); try { JAXBContext jaxbContext = JAXBContext.newInstance(StampaModuloPrivacyRequest.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 新增逻辑:用StringWriter捕获XML内容 StringWriter sw = new StringWriter(); jaxbMarshaller.marshal(input, sw); // 将生成的XML字符串设置到响应对象 String xmlString = sw.toString(); stampaModuloPrivacyResponse.setXMLString(xmlString); // 如果还需要在控制台打印XML,可以保留这行 // jaxbMarshaller.marshal(input, System.out); } catch (JAXBException e) { e.printStackTrace(); } return stampaModuloPrivacyResponse; }
简单说下原理:StringWriter是一个基于内存的字符输出流,它会把写入的内容暂存在内部的字符串缓冲区里,调用toString()就能直接提取出完整的XML字符串,刚好匹配你要给stampaModuloPrivacyResponse设置字符串的需求。
内容的提问来源于stack exchange,提问作者Filomena
相关产品推荐
相关产品推荐

