I have been assigned a work to validate a XML against an XSD and if everything passed will parse the XML so that can import the same in to my system.
My Question is that what is the best way to validate an XML against the XSD and which is the best API for parsing the XML in to my domain object.
Looking for valuable suggestions
xsd is the XML schema you will use as input to the JAXB binding compiler, and from which schema-derived JAXB Java classes will be generated. For the Customize Inline and Datatype Converter examples, this file contains inline binding customizations.
We can use Eclipse IDE to easily generate XML from the XSD file. Just follow the below steps to get XML from XSD. Select XSD File in project, right click for Menu and select Generate > XML File… Provide the XML file Name and XML File location in the popup window.
Part 1 - Validate XML
You can use the javax.xml.validation APIs for this.
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaURL = // The URL to your XML Schema;
Schema schema = sf.newSchema(schemaURL);
Validator validator = schema.newValidator();
validator.validate(xml);
Part 2 - OXM
Regarding the second part of your question, the best API for parsing XML into the domain object is JAXB. JAXB is a specification with multiple implementations. I lead the MOXy JAXB implementation that contains useful extensions such as XPath based mapping.
You could always do the validation during the conversion of XML to objects:
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaURL = // The URL to your XML Schema;
Schema schema = sf.newSchema(schemaURL);
unmarshaller.setSchema(schema);
JAXBElement<Customer> element = (JAXBElement<Customer>) unmarshaller.unmarshal(xml);
Customer customer = elemnt.getValue();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With