Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML with XSD JAVA

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

like image 1000
umesh Avatar asked Oct 08 '10 18:10

umesh


People also ask

What is XSD in Java?

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.

Can we generate XML from XSD?

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.


1 Answers

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();
like image 65
bdoughan Avatar answered Nov 09 '22 02:11

bdoughan