Convert a java object to XML stored in a String object using JAXB

In the last tutorial, i showed how to write a java object to an XML file and to convert an XML file to a java object.Today we are looking at a tutorial by which we can convert a java object to an XML and store that XML in a string rather than a file.

In this example we are going to use StringWriter.  StringWriter is a character stream that collects its output in a string buffer, which can then be used to construct a string.

Here is the complete code that converts a java object to XML

StringWriter sw = new StringWriter();
JAXB.marshal(javaObject, sw);

So in the above code we create a StringWriter and pass it onto JAXB.marshal(Object jaxbObject, Writer xml) method of JAXB which writes a Java object tree to XML and store it to the specified location.

And then if we want to convert the xml string back to the Java Object we can do it by using StringReader. StringReader is a character stream whose source is a string.

MyObject unmarshalledObject = JAXB.unmarshal(new StringReader(string), MyObject.class);

Here we are using  JAXB.unmarshal(Reader xml, Class<T> type),  This method reads in a Java object tree from the given XML input.

Let us have a look at complete example:

package my.test;

package my.test;

import javax.xml.bind.JAXB;

public class JAXBTutorial {
    public static void main(String[] args) throws IOException {
        Person karlPerson = new Person();
        StringWriter sw = new StringWriter();
        JAXB.marshal(karlPerson, sw);
        System.out.println("--- start: output of marshalling ----");
        System.out.println("--- end: output of marshalling ----");
        System.out.println("--- start: output of unmarshalling ----");
        Person karlUnmarshalled = JAXB.unmarshal(new StringReader(sw.toString()), Person.class);

    static class Person implements Serializable {
        private static final long serialVersionUID = 2020790181274222998L;
        private String name;

        public String getName() {
            return name;

        public void setName(String name) {
   = name;


--- start: output of marshalling ----
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

--- end: output of marshalling ----

--- start: output of unmarshalling ----

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.