Java HTML / XML How to - Catch jaxb catch exception if field is not found in java class








Question

We would like to know how to catch jaxb catch exception if field is not found in java class.

Answer

Java Model (Root)

import javax.xml.bind.annotation.XmlRootElement;
/*from w ww  . j  a v  a 2 s .  c o m*/
@XmlRootElement
public class Root {

    private String foo;

    public String getFoo() {
        return foo;
    }

    public void setFoo(String foo) {
        this.foo = foo;
    }

}

Demo

import java.io.StringReader;
import javax.xml.bind.*;
/* ww  w .  jav  a  2 s  . co  m*/
public class Main {

    private static final String XML = "<root><foo>Hello</foo><bar>World</bar></root>";

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        // Unmarshal #1 = Default Unmarshal
        System.out.println("Unmarshal #1");
        Root root = (Root) unmarshaller.unmarshal(new StringReader(XML));
        marshaller.marshal(root, System.out);

        // Unmarshal #2 - Override Default ValidationEventHandler
        System.out.println("Unmarshal #2");
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(ValidationEvent event) {
                System.out.println(event.getMessage());
                return false;
            }
        });
        unmarshaller.unmarshal(new StringReader(XML));
    }

}