Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java object to XML string

Tags:

java

xml

jaxb

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?

like image 593
Bob Avatar asked Nov 16 '14 16:11

Bob


People also ask

Can we convert String to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

What is the JAXB process for converting an XML document to Java object called?

The process of converting objects to XML is called marshalling (How to convert object to XML using JAXB) and the conversion of XML to objects is called unmarshalling in JAXB terms.


2 Answers

You can use the Marshaler's method for marshaling which takes a Writer as parameter:

marshal(Object,Writer)

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.

So doing:

StringWriter sw = new StringWriter(); jaxbMarshaller.marshal(customer, sw); String xmlString = sw.toString(); 
like image 195
A4L Avatar answered Sep 18 '22 03:09

A4L


A convenient option is to use javax.xml.bind.JAXB:

StringWriter sw = new StringWriter(); JAXB.marshal(customer, sw); String xmlString = sw.toString(); 

The [reverse] process (unmarshal) would be:

Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class); 

No need to deal with checked exceptions in this approach.

like image 33
juliaaano Avatar answered Sep 20 '22 03:09

juliaaano