Reputation: 3785
I'm looking for a way to validate my XML files against an internal schema. Currently this is my code.
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser;
parser = factory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
final XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SAXErrorHandler());
reader.parse(new InputSource(doc));
Well what it does is reporting validation errors as warnings if it a non fatal error and parsing can continue. This is great because I can see more errors then if it just breaks and throws an exception.
However what it not does is making information available in the code to me so I can have a Method boolean validate()
to return whether there is or there is not an error (warning)
So I thought about an own instance of ErrorHandler with a property that I can grab after parsing has finished but that sounds not cool to me :)
The next thing is parsing that parsing like this takes some time and just using a validator could be significantly faster (and yes it is time critical here ;)) but because I need the internal schemas for validation I don't know how to not fully parse.
Upvotes: 0
Views: 529
Reputation: 35372
public static boolean validate(String xml)
throws ParserConfigurationException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
// custom error handler
// ignore warning, throw on error and fatal
// (we will catch later to return false!)
reader.setErrorHandler(
new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNING : " + e.getMessage()); // do nothing
}
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROR : " + e.getMessage());
throw e;
}
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;
}
}
See SAX ErrorHandler
Upvotes: 0
Reputation: 53694
Yes, you want to use a custom ErrorHandler which tracks whether or not an error was encountered (not sure what you think that sounds "not cool").
As for "validating" vs. "parsing", how do you expect to validate a document without parsing it?
Upvotes: 1