Validate object against xsd / generated object Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Validate object against xsd / generated object without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have an application where I have generated Java classes from an xsd schema. I also have a rest service using jax-rs. I need to validate the input to the POST methods, to ensure that comply with the rules set in the xsd schema.

public void addPerson(Person person) {

    //Need to validate Person object 


The Person object is a class generated from the xsd. Can I assume that the object complies with the xsd, or will I have to validate the object? In that case, how can I validate?

I know this is a newbie question, but I hope someone can help.


I haven’t tried myself, but I think the following code would work.

JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();

according to your namespace, use

marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "yourXSD.xsd");


marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "yourXSD.xsd");

and then marshal the person instance, if no exception, that means the person instance is fine. Otherwise, it’s not.

Oh, I forgot on thing. Before you marshal it, remember to setSchema()

    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File("your.xsd"));

    marshaller.setEventHandler(new ValidationEventHandler() {
      public boolean handleEvent(ValidationEvent event) {
        return false; //to stop the marshal if anything happened
We are here to answer your question about Validate object against xsd / generated object - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji