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

如何通过JAXB API在保存前从JAXBElement获取XML字符串

轻松获取JAXB对象的XML字符串

嘿,这个需求超容易搞定的,不用绕弯子去读文件,直接用JAXB的Marshaller搭配StringWriter就能从你的Wrapper<Hopital>实例里直接拿到XML字符串,改动代码量极少,看具体实现:

Wrapper<Hopital> hopitaux = new Wrapper<Hopital>();
hopitaux.setElements(getListe());

// 核心代码:直接生成XML字符串
JAXBContext context = JAXBContext.newInstance(Wrapper.class, Hopital.class);
Marshaller marshaller = context.createMarshaller();
// 可选:设置格式化输出,让XML结构更清晰(不需要的话可以删掉这行)
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

StringWriter stringWriter = new StringWriter();
marshaller.marshal(hopitaux, stringWriter);
// 这里就是你要的XML字符串啦
String xmlContent = stringWriter.toString();

// 如果之后还是需要写入文件,直接用这个字符串就行(和你原来的逻辑兼容)
BufferedWriter writer = new BufferedWriter(new FileWriter(hfile));
writer.write(xmlContent);
writer.close();

关键说明:

  • StringWriter是一个内存中的字符流,JAXB会把对象序列化的内容直接写到这个流里,而不是磁盘文件
  • 调用stringWriter.toString()就能一次性取出完整的XML字符串,完全不需要额外读取文件
  • 如果你想要格式化后的XML(带缩进、换行),就保留marshaller.setProperty那一行;要是追求紧凑格式,直接删掉就行

这样既满足了你的需求,又和原来的代码逻辑完美兼容,改动极小~

内容的提问来源于stack exchange,提问作者Boussadjra Brahim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:07:02