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.
Validate xml created using jaxb against an xsd file
Asked Answered
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? –
Affricate
You can set Schema and ValidationEventHandler on the marshaller itself. It will validate against the schema during marshalling. See docs.oracle.com/javase/6/docs/api/javax/xml/bind/… –
Tantalous
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.
You can validate before marshalling as well: JAXBSource source = new JAXBSource(jaxbContext, objectBeingMarshalled); validator.validate(source); –
Tantalous
i am getting this exeception sax exception :The processing instruction target matching "[xX][mM][lL]" is not allowed. –
Bascule
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 :gonithethinker.blogspot.com/2012/06/… @AutoMeta –
Roadhouse
© 2022 - 2024 — McMap. All rights reserved.