1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
   | import java.io.IOException;
 
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
 
 
 
 
public class XSDValidator {
 
	static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
 
	static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
 
	static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
 
	static boolean isValid;
 
	static {
		isValid = false;
	}
 
	public static boolean validXMLWithSAX(String xmlFile, String xsdFile) {
		isValid = true;
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			spf.setNamespaceAware(true);
			spf.setValidating(true);
			SAXParser sp = spf.newSAXParser();
			sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
			sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);
			sp.parse(xmlFile, new DefaultHandler(){
				public void fatalError(SAXParseException e) {
					System.out.println(e.getMessage());
					System.out
					.println("Erreur de validation XSD - Erreur fatal");
					isValid = false;
				}
 
				public void error(SAXParseException e) {
					System.out.println(e.getMessage());
					System.out.println("Erreur de validation XSD - Erreur");
					isValid = false;
				}
 
				public void warning(SAXParseException e) {
					System.out.println(e.getMessage());
					System.out.println("Erreur de validation XSD - Warning");
					isValid = false;
				}
			});
		} catch (SAXException se) {
			System.out.println(se);
			return false;
		} catch (ParserConfigurationException pce){
			System.out.println(pce);
			return false;
		} catch (IOException ioe){
			System.out.println(ioe);
			return false;
		}
		return isValid;
	} | 
Partager