From XML to object

We have seen how easy is to marshal a Java object to XML when using JAXB, now I am showing you how to unmarshal an XML in a (compatible) Java object using the same library.

We have this XML fragment:
<user id="42" rating="4.2">Bill</user>
And we want to get from it an instance of the class User, as defined in the previous post. The (minor) nuisance is that I have to annotate User so that JAXB knows how it should map its data member to the XML elements, values, and attributes. Once this is done, we get the job done in a matter of few lines:
public User xml2Obj(String xml) { // 1
    try {
        JAXBContext ctx = JAXBContext.newInstance(User.class); // 2
        Unmarshaller um = ctx.createUnmarshaller(); // 3

        StringReader sr = new StringReader(xml);
        User user = (User) um.unmarshal(sr); // 4
        return user;
    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    }
}
1. This function gets in input the XML to be unmarshalled, and gives back the resulting User object (or null, in case of error).
2. A JAXB context is needed to do the magic, and it should know on which class it operates.
3. A JAXB marshaller is the guy that is going to do the dirty job.
4. To keep the unmarshaller code simple, it has been designed to operate on readers. So, the XML String is passed to a StringReader to adapt it to the JAXB expectations.

The full Java source code for the User class and a Main class using it are on github. The example includes both marshalling (as seen in the previous post) and unmarshalling.

Go to the full post