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 java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXB;

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

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

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

output:

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

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

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

Leave a Comment

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