Task: XML validation





Java: import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;

import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import javax.xml.ws.Holder;

import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class XmlValidation {
	public static void main(String... args) throws MalformedURLException {
		URL schemaLocation = new URL("http:
		URL documentLocation = new URL("http:
		if (validate(schemaLocation, documentLocation)) {
			System.out.println("document is valid");
		} else {
			System.out.println("document is invalid");
		}
	}

	
	public static boolean minimalValidate(URL schemaLocation, URL documentLocation) {
		SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
		try {
			Validator validator = factory.newSchema(schemaLocation).newValidator();
			validator.validate(new StreamSource(documentLocation.toString()));
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	
	public static boolean validate(URL schemaLocation, URL documentLocation) {
		SchemaFactory factory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
		final Holder<Boolean> valid = new Holder<>(true);
		try {
			Validator validator = factory.newSchema(schemaLocation).newValidator();
			
			validator.setErrorHandler(new ErrorHandler(){
				@Override
				public void warning(SAXParseException exception) {
					System.out.println("warning: " + exception.getMessage());
				}

				@Override
				public void error(SAXParseException exception) {
					System.out.println("error: " + exception.getMessage());
					valid.value = false;
				}

				@Override
				public void fatalError(SAXParseException exception) throws SAXException {
					System.out.println("fatal error: " + exception.getMessage());
					throw exception;
				}});
			validator.validate(new StreamSource(documentLocation.toString()));
			return valid.value;
		} catch (SAXException e) {
			
			return false;
		} catch (Exception e) {
			
			System.err.println(e);
			return false;
		}
	}
}




VB: Option explicit

Function fileexists(fn) 
  fileexists= CreateObject("Scripting.FileSystemObject").FileExists(fn)
End Function

Function xmlvalid(strfilename)
  Dim xmldoc,xmldoc2,objSchemas 
  Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
  
  If fileexists(Replace(strfilename,".xml",".dtd")) Then
    xmlDoc.setProperty "ProhibitDTD", False
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
  ElseIf fileexists(Replace(strfilename,".xml",".xsd")) Then
    xmlDoc.setProperty "ProhibitDTD", True
    xmlDoc.setProperty "ResolveExternals", True 
    xmlDoc.validateOnParse = True
    xmlDoc.async = False
    xmlDoc.load(strFileName)
    
    
    Set xmlDoc2 = CreateObject("Msxml2.DOMDocument.6.0")
    xmlDoc2.validateOnParse = True
    xmlDoc2.async = False
    xmlDoc2.load(Replace (strfilename,".xml",".xsd"))
    
    
    Set objSchemas = CreateObject("MSXML2.XMLSchemaCache.6.0")
    objSchemas.Add "", xmlDoc2
  Else 
    Set xmlvalid= Nothing:Exit Function
  End If
  
  Set xmlvalid=xmldoc.parseError 
End Function



Sub displayerror (parserr) 
  Dim strresult
  If parserr is Nothing Then 
    strresult= "could not find dtd or xsd for " & strFileName
  Else   
    With parserr
     Select Case .errorcode
      Case 0 
        strResult = "Valid: " & strFileName & vbCr
      Case Else
        strResult = vbCrLf & "ERROR! Failed to validate " & _
        strFileName & vbCrLf &.reason & vbCr & _
        "Error code: " & .errorCode & ", Line: " & _
        .line & ", Character: " & _
        .linepos & ", Source: """ & _
        .srcText &  """ - " & vbCrLf 
 
      End Select
    End With
  End If
  WScript.Echo strresult
End Sub


Dim strfilename






strfilename="shiporder.xml"
displayerror xmlvalid (strfilename)