I'm parsing XML files that are on the internal storage in my app using SAX parser. This works without any problems but I also want to validate the files before parsing.
I've done some research and have found the following class to work with Eclipse Mars and Windows 7 (source: http://www.rgagnon.com/javadetails/java-0669.html):
public static boolean validateWithExtXSDUsingSAX(String xml, String xsd)
throws ParserConfigurationException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI));
SAXParser parser = null;
try {
factory.setSchema(schemaFactory.newSchema(new Source[] { new StreamSource(xsd) }));
parser = factory.newSAXParser();
} catch (SAXException se) {
System.out.println("SCHEMA : " + se.getMessage()); // problem in the XSD itself
return false;
}
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNING: " + e.getMessage()); // do nothing
}
@Override
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROR : " + e.getMessage());
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("FATAL : " + e.getMessage());
throw e;
}
});
reader.parse(new InputSource(xml));
return true;
} catch (ParserConfigurationException pce) {
throw pce;
} catch (IOException io) {
throw io;
} catch (SAXException se) {
return false;
}
}
But when I want to use this class with Android Studio 1.3 and Android 5.1 (API 22) I only get errors:
java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:192)
But according to the dev page this should be correct: http://developer.android.com/reference/javax/xml/validation/SchemaFactory.html
Do I have to use a different form of validating my XML files on Android?
Thanks in advance
PS: I have to use SAX, there i sno possibility to use another parser.
EDIT: When using this solution by VenomFangs I get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'javax.xml.validation.Validator javax.xml.validation.Schema.newValidator()' on a null object reference