[英]Java - Getting XML content from JAXBElement using JAXB API
我有以下代码,它使用 JAXB API 将医院数据保存到 XML 文件中,它工作正常,但我想在保存之前将 XML 内容从element
( JAXBElement
的实例)获取到String
对象中,而无需再次读取文件,如何我可以用几行代码做到这一点吗?
Wrapper<Hopital> hopitaux = new Wrapper<Hopital>();
hopitaux.setElements(getListe());
BufferedWriter writer = new BufferedWriter(new FileWriter(hfile));
JAXBContext context = JAXBContext.newInstance(Wrapper.class, Hopital.class, Service.class, Medecin.class);
JAXBElement<Wrapper> element = new JAXBElement<Wrapper>(new QName("hopitaux"), Wrapper.class, hopitaux);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_ENCODING, "iso-8859-15");
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(element, System.out);
m.marshal(element, writer);
writer.close();
将其StringWriter
到StringWriter
以捕获字符串中的输出。 不过,我认为,您必须将编码从Marshaller
移动到将字符串写入文件的位置。
StringWriter stringWriter = new StringWriter();
m.marshal(element, stringWriter);
String content = stringWriter.toString();
try (BufferedWriter writer = Files.newBufferedWriter(hfile,
Charset.forName("ISO-8859-15"))) {
writer.write(content);
}
(假设hfile
是Path
,否则根据需要使用Paths.get(hfile)
或hfile.toPath()
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.