/* xerces-based parser written by Terri Liebowitz Schwartz of SDSC (see CIPRES license). Executable takes three arguments: path-to-instance-document path-to-xml-schema namespace */ package validator; import java.io.File; import java.io.FileReader; import java.util.Properties; import org.apache.xerces.parsers.DOMParser; import org.xml.sax.InputSource; /* Note that first implementation of againstXSD is commented out and the real implementation has a third optional argument, a namespace. If the xml document references a schema, and it refers to a schema file that exists, that schema will be used. It doesn't matter whether you specify a namespace or valid xsd file when invoking this, all that will be ignored if the document contains a reference to a schema file that exits. If the document references a schema file that doesn't exist, or doesn't reference a schema, then you can specify the schema and namespace (if any) here. */ public class XmlValidator { /** * @param xmlFilepath filepath to the xml file to be validated * @param xsdFilepath filepath to the xsd file that the gui xml file * specified by xmlFilepath should be validated against * @return error message generated by SAX parser or null if no * errors are detected */ public static String againstXSD(final String xmlFilepath, final String xsdFilepath, final String namespace) { try { // make sure both paths specify a valid file File config_fp = new File(xmlFilepath); if (!config_fp.exists()) return "Unable to open file " + xmlFilepath; config_fp = new File(xsdFilepath); if (!config_fp.exists()) return "Unable to open file " + xsdFilepath; final DOMParser parser = new DOMParser(); parser.setFeature("http://xml.org/sax/features/validation", true); parser.setFeature("http://apache.org/xml/features/validation/schema", true); if (namespace == null || namespace.trim().equals("")) parser.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation", xsdFilepath); else parser.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation", namespace.trim() + " " + xsdFilepath); parser.parse(new InputSource(new FileReader(xmlFilepath))); return null; } catch (final Exception e) { e.printStackTrace(); return e.getMessage(); } } public static void main(final String args[]) { final Properties p = System.getProperties(); final String xml = p.getProperty("xml"); final String xsd = p.getProperty("xsd"); final String ns = p.getProperty("ns"); if (xml == null || xsd == null) { System.out.println("Two system properties are required, xml=xml_file and xsd=xsd_file"); System.out.println("ns=namespace is optional."); System.exit(1); } final String retval = againstXSD(xml, xsd, ns); if (retval == null) { System.exit(0); } System.out.println("Validation error: " + retval); System.exit(1); } }