Yes, yes I know that lots of questions were asked about this topic. But I still cannot find the solution to my problem. I have a property annotated Java object. For example Customer, like in this example. And I want a String representation of it. Google reccomends using JAXB for such purposes. But in all examples created XML file is printed to file or console, like this:
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
String xmlString = ...
You can use the Marshaler's method for marshaling which takes a Writer as parameter:
and pass it an Implementation which can build a String object
Direct Known Subclasses: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter
Call its toString method to get the actual String value.
StringWriter sw = new StringWriter(); jaxbMarshaller.marshal(customer, sw); String xmlString = sw.toString();