0

我有以下代码,它使用 JAXB API 将医院数据保存到 XML 文件中,它工作正常,但我想在保存之前将 XML 内容从(的实例)获取到一个String对象而不再次读取文件,我该怎么做几行代码?elementJAXBElement

    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();
4

1 回答 1

1

将其编组到 aStringWriter以捕获字符串中的输出。不过,我认为,您必须将编码从 移动到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);
}

(假设hfilePath,否则使用Paths.get(hfile)hfile.toPath()酌情使用。)

于 2018-04-19T18:13:37.333 回答