1

I have a class annotated with jaxb annotations and I want to configure the unmarshaller to fail the unmarshalling if there are missing attributes.

Let's say, I'm having the below class, and I would like to fail the unmarshaling if the EventId attribute is missing from the xml, but instead, it is set to null.

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "event")
public class Event {

    @XmlAttribute(name = "EventId", required="true")
    private Integer eventId;
    ...
}

Unmarshalling code:

JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[]{Events.class}, null);
StringReader xml = new StringReader(data);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setEventHandler(new DefaultValidationEventHandler());
unmarshaller.unmarshal(xml);

Am I missing something? Should I configure somehow the unmarshaller to fail if there are missing "required" attributes?

Thanks!

Cristi
  • 190
  • 2
  • 10

1 Answers1

0

You can validate XML documents before unmarshalling by providing a schema: https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/Unmarshaller.html#setSchema-javax.xml.validation.Schema-

Puce
  • 37,247
  • 13
  • 80
  • 152
  • 1
    Yes, I know. I was wondering if there is any way of doing it without a schema, since I've done the mappings with annotations. – Cristi May 28 '15 at 11:16
  • @Cristi Have you found any way to do validation without schema and just annotations? – pavi2410 Apr 22 '20 at 10:18