Validating XML with XML schema (XSD)

Guys believe me today I struggled a lot trying to do a very simple thing: Validating an xml file with my XSD( XML Schema), using a SAX parser(apache). I tried simple standalone program and in one shot I got itworking and now I want it to inside my web application. I added it(XSD)to the resources(classpath) and deployed my app to the tomcat but unfortunately I started getting the error "cvc-elt.1: Cannot find the declaration of element 'Root'". So I started checking my input xml m the XSD and all. All is well formed and Root is there. Then question remains where I went wrong. After some observation I found that the parser(com.sun.org.apache.xerces.internal.parsers.SAXParser) not able to get the XSD itself :( . I checked my project structure and but all things are at place. So I started putting the XSD in possible locations where this guy will look. But no luck. By now I'm pretty sure that culprit is not the directory structure. After some internet search I found thatparser properties value should be URL but I didn't want the XSD to be publicly available. Unfortunately, I didn't find how to do that directly on the Internet. So after trying things ,I came to know that which I didn't knew earlier the simple thing I missed it is that JAVA can generate an URL pointing to a file residing in the classpath. so here's the code :

SAXBuilder builder = new SAXBuilder("com.sun.org.apache.xerces.internal.parsers.SAXParser",true);
builder.setFeature("http://xml.org/sax/features/validation", true);
builder.setFeature("http://apache.org/xml/features/validation/schema",true);
builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/my.properties"));
URL schemaUrl = getClass().getResource(properties.getProperty("my.xsd"));
builder.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",schemaUrl);
builder.build(inXML);

I haven't used any ErrorHandler since just want to show the exact error message coming from XSD validation and halt. Good luck!!

Posted at at 6:24 AM on Friday, January 14, 2011 by Posted by Ravindra Nikam | 0 comments   | Filed under: ,