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
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
But I have to use this object and send over network in XML format. So I want to get a String which represents XML.
String xmlString = ...
sendOverNetwork(xmlString);
How can I do this?
To convert an Object to XML in Java
Customer.java
ConvertObjToXML.java
Try with this example..
Some Generic code to create XML Stirng
object --> is Java class to convert it to XML
name --> is just name space like thing - for differentiate
A convenient option is to use javax.xml.bind.JAXB:
The reverse process (unmarshal) would be:
No need to deal with checked exceptions in this approach.
Use this function to convert Object to xml string (should be called as convertToXml(sourceObject, Object.class); )-->
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
Use this function to convert xml string to Object back --> (should be called as createObjectFromXmlString(xmlString, Object.class))
public static T createObjectFromXmlString(String xml, Class clazz) throws JAXBException, IOException{
As A4L mentioning, you can use StringWriter. Providing here example code: