| Refresh | Home EGTry.com

use msxml to validate xml against schema


use Win32::OLE;
use strict;

unless ($ARGV[1])
{
    print "Usage: schemaVAlidate xmlfile xsdfile\n";
    exit;
}


validateFile($ARGV[0], $ARGV[1]);


sub validateFile
{
    my $xmlFile=shift;
    my $schemaFile=shift;

    print "validate $xmlFile against $schemaFile\n\n";
    unless (-e $xmlFile and -e $schemaFile) 
    {
        die "can not open $xmlFile or $schemaFile\n";
    }     
     
    # Create a schema cache and add books.xsd to it.
    #my $xs = new Win32::OLE("MSXML2.XMLSchemaCache.4.0");
    my $xs = new Win32::OLE("MSXML2.XMLSchemaCache.6.0");
    $xs->add("", $schemaFile);

    #Create an XML DOMDocument object.
    #my $xd = new Win32::OLE("MSXML2.DOMDocument.4.0");
    my $xd = new Win32::OLE("MSXML2.DOMDocument.6.0");

    # Assign the schema cache to the DOMDocument's
    # schemas collection.
    $xd->{"schemas"} = $xs;

    # Load books.xml as the DOM document.
    $xd->{"async"} = 0;
    $xd->{"validateOnParse"}=1;
    $xd->{"resolveExternals"} = 1;
    $xd->load($xmlFile);
    # Return validation results in message to the user.
    my $parseError=$xd->{"parseError"};
    if ($parseError->{"errorCode"} != 0)
    {
         print "Validation failed on " . $xmlFile . 
                "\n=====================" .
                "\nReason: " . $parseError->{"reason"} . 
                "\nSource: " . $parseError->{"srcText"} . 
                "\nLine: " . $parseError->{"line"} . "\n";
    }
    else 
    {
        print "validate success.\n";
    }
}