簡體   English   中英

Java - 使用 JAXB API 從 JAXBElement 獲取 XML 內容

[英]Java - Getting XML content from JAXBElement using JAXB API

我有以下代碼,它使用 JAXB API 將醫院數據保存到 XML 文件中,它工作正常,但我想在保存之前將 XML 內容從elementJAXBElement的實例)獲取到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();

將其StringWriterStringWriter以捕獲字符串中的輸出。 不過,我認為,您必須將編碼從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() 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM