Java Utililty Methods XML Validate

List of utility methods to do XML Validate

Description

The list of methods to do XML Validate are organized into topic(s).

Method

voidvalidateXml(final Schema schema, final byte[] xmlBytes)
validate Xml
validateXml(schema, new ByteArrayInputStream(xmlBytes));
voidvalidateXml(InputStream xml, InputStream xsd)
validate Xml
try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = dbf.newDocumentBuilder().parse(xml);
    validateXml(doc, xsd);
} finally {
    closeStream(xml);
    closeStream(xsd);
...
booleanvalidateXML(String schemaPath, String xmlPath)
validate XML
try {
    String schemaLang = "http://www.w3.org/2001/XMLSchema";
    SchemaFactory factory = SchemaFactory.newInstance(schemaLang);
    Schema schema = factory.newSchema(new StreamSource(schemaPath));
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(xmlPath));
} catch (Exception ex) {
    return false;
...
voidvalidateXML(String xml, String schemaURI, DefaultHandler handler)
This method will validate the the XML String passed in afainst the Schema Location passed in as a parameter.
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.XML_NS_URI);
StreamSource ss = new StreamSource(schemaURI);
Schema schema = sf.newSchema(ss);
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setSchema(schema);
spf.setNamespaceAware(true);
javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
saxParser.parse(new ByteArrayInputStream(xml.getBytes()), handler);
...
voidvalidateXMLFile(String filename, String schemaFile)
Validate the contents of a file against an XML Schema.
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File(filename));
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(schemaFile));
Validator validator = schema.newValidator();
validator.validate(new DOMSource(document));
voidvalidateXmlOnSchema(File xmlSchema, Source sourceXml)
Validates XML on a XMLschema
Schema schema = newSchema(xmlSchema);
try {
    schema.newValidator().validate(sourceXml);
} catch (Exception e) {
    throw new RuntimeException(
            "Could not validate '" + sourceXml.getSystemId() + "' with '" + xmlSchema.getName() + "'!", e);