Search code examples
javaxmljaxbjaxbelement

Java - Getting XML content from JAXBElement using JAXB API


I have the following code which save hospitals data into XML file using JAXB API, it works fine but i want to get the XML content into a String object from element (the JAXBElement's instance ) before saving it without reading the file again, How can i do that in few lines of code ?

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

Solution

  • Marshal it to a StringWriter to capture the output in a string. You will have to move the encoding from the Marshaller to the point where you write out the string to the file, though, I think.

    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);
    }
    

    (Assuming hfile is a Path, otherwise use Paths.get(hfile) or hfile.toPath() as appropriate.)