JAXB tutorial part 3: marshalling and unmarshalling data

How to unmarshall and marshall data to XML using JAXB.

In the last screencast I generated classes from  XSD file. Now I will use  them to work with XML file.

To read data from this XML file we must create an instance of JAXBContext. This class has a constructor, that requires either package where are generated classes, or some class from this package. In this class are methods createMarshaller() and createUnmarshaller(). Using unmarshaller we can unmarshall (read data) from XML file to objects. Using marshaller we can save objects to XML files.

I will create unmarshaller and unmarshal file sitemap.xml. Notice that using this operation I will get instance of object annotated with @XmlRootElement. Next I can easily work with XML using Java objects. For example I will print all URLs in this file.

I can also easily modify XML, for example I will create some new URL and add it to list and next marshal the whole XML to another file.

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Urlset urlset = (Urlset) unmarshaller.unmarshal(new File("sitemap.xml"));
    List<TUrl> list = urlset.getUrl();
    for (TUrl tUrl : list) {
    TUrl url = new TUrl();
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(urlset, new File("sitemap2.xml"));