You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:26:57