9

I have a xml file created using jaxb. I need to validate it against a xsd document. Is it possible to just do validation without unmarshalling. I need to then print the errors in the xml file.

Anand B
  • 2,997
  • 11
  • 34
  • 55
  • One of the main advantages of generating a binding code from xsd and then using the code to create an instance xml is to output a valid and well-formed xml. I am not sure why you want to validate it again? – Aravind Yarram Jun 08 '12 at 13:14
  • 1
    You can set Schema and ValidationEventHandler on the marshaller itself. It will validate against the schema during marshalling. See http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/Marshaller.html#setSchema(javax.xml.validation.Schema) – Ritesh Jun 10 '12 at 00:30

1 Answers1

12

Yes you can use validator found in java from 1.5. here is the reference doc

Apart from it you can use dom based or stream based API to validate your XML document against xsd file. If you wish to use SAX API for your task then hear is the example:

try {
    String schemaLang = "http://www.w3.org/2001/XMLSchema";

    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

    Schema schema = factory.newSchema(new StreamSource("sample.xsd"));
    Validator validator = schema.newValidator();

    validator.validate(new StreamSource("test.xml"));

} catch (SAXException e) {
    System.out.println(" sax exception :" + e.getMessage());
} catch (Exception ex) {
    System.out.println("excep :" + ex.getMessage());
}

Otherwise you can use DOM, DOM4J or XOM API. For further reference you can see here.

There is a related answer in stackoverflow also.

Community
  • 1
  • 1
Asraful
  • 1,241
  • 18
  • 31
  • 1
    You can validate before marshalling as well: JAXBSource source = new JAXBSource(jaxbContext, objectBeingMarshalled); validator.validate(source); – Ritesh Jun 10 '12 at 00:38
  • i am getting this exeception sax exception :The processing instruction target matching "[xX][mM][lL]" is not allowed. – AutoMEta Feb 14 '13 at 11:09
  • it mean that in your XML starting it has some space , remove space or anything else at the beginning of your XML , follow the link :http://gonithethinker.blogspot.com/2012/06/processing-instruction-target-matching.html @AutoMeta – Asraful Feb 19 '13 at 14:47