User Tools

Site Tools


technology:java:xml_schema_validator

XML Schema Validator

Once upon a project, I had a hard time deploying my code to an application server. Turns out, the application server on the production machine had stricter XML validation rules than the one on my laptop. So…how do I validate my XML files in advance? I couldn't find anything, so I wrote my own.

This class parses an XML file and validates it against its DTD. This ensures the document is well-formed XML, that all the namespaces are valid, and that the document matches its DTD. It uses classes from the Apache Xerces project.

Schema and namespace validation can be turned off by commenting out the appropriate feature in the code

import java.io.*;
import javax.swing.*;
import org.xml.sax.*;
import javax.xml.parsers.*;
 
class XMLValidator implements ErrorHandler {
    private boolean ERROR = false;
 
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("No Filename given.");
            System.exit(1);
        }
 
        XMLValidator xmlv = new XMLValidator();
        int status = xmlv.validate(args[0]);
        System.exit(status);
 
    }
 
    public int validate(String filename) {
        try {
            // setup SAX parser
            Class.forName("org.apache.xerces.parsers.SAXParser");
            XMLReader xr = new org.apache.xerces.parsers.SAXParser();
            xr.setFeature("http://xml.org/sax/features/validation", true);
            xr.setFeature("http://apache.org/xml/features/validation/schema", true);
            xr.setFeature("http://xml.org/sax/features/namespaces", true);
            xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
            xr.setErrorHandler(this);
 
            //open & parse file
            InputStream in = new FileInputStream(new File(filename));
            xr.parse(new InputSource(in));
 
            //display status if all went well
            if (!ERROR)System.out.println("Document validates OK.");
 
        } catch (SAXException se) {
            System.out.println("SAX Exception:  " + se.getMessage());
            ERROR = true;
        } catch (IOException ioe) {
            System.out.println("IO Exception:  " + ioe.getMessage());
            ERROR = true;
        } catch (ClassNotFoundException cnfe) {
            System.out.println("Parser Not Found");
            ERROR = true;
        } finally {
            return (ERROR ? 1 : 0);
        }
 
    }
 
    /*--------------------------------------
     -- 3 ErrorHandler interface methods  --
     --------------------------------------*/
    public void error(SAXParseException spe) {displayInfo("Error", spe);}
    public void fatalError(SAXParseException spe) {displayInfo("Fatal Error", spe);}
    public void warning(SAXParseException spe) {displayInfo("Warning", spe);}
 
 
    private void displayInfo(String errorType, SAXParseException spe){
        System.out.println(errorType+" in Parsing:\n  Line " + spe.getLineNumber()
                + ", Column " + spe.getColumnNumber() + "\n  Message: "
                + spe.getMessage());
        ERROR = true;
 
    }
};
/home/cfreyer/public_html/data/pages/technology/java/xml_schema_validator.txt · Last modified: 2009/09/09 10:24 by Chris Freyer