Sdílet prostřednictvím


Jscript Code (schemaCache.js)

 

This topic provides JScript example code.

Try It!

  1. Copy the first XML data file from the resource files, and paste it into a text file. Save the file as sc-valid.xml.

  2. Copy the second XML data file from the resource files, and paste it into a text file. Save the file as sc-notValid.xml, in the same directory where you saved sc-valid.xml.

  3. Copy the XSD schema file from the resource files, and paste it into a text file. Save the file as sc.xsd, in the same directory you used in previous steps.

  4. Copy the JScript listing above, and paste it into a text file. Save the file as schemaCache.js, in the same directory you used in previous steps.

  5. Double click the schemaCache.js file from Windows Explorer to launch the application. Alternatively, you can type "cscript schemaCache.js" from a command prompt.

    Note Under operating systems other than Windows 2000 or Windows XP, you might need to install Windows Scripting Host (wscript.exe), if it is not already installed.

  6. Verify that your output is the same as that listed in the output for this example.

schemaCache.js

var sOutput = validateFile("sc-valid.xml");
sOutput = sOutput + validateFile("sc-notValid.xml");
WScript.Echo(sOutput);

function validateFile(strFile)
{
    // Create a schema cache and add books.xsd to it.
    var xs = new ActiveXObject("MSXML2.XMLSchemaCache.6.0");
    xs.add("urn:books", "sc.xsd");

    // Create an XML DOMDocument object.
    var xd = new ActiveXObject("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 = false;
    xd.validateOnParse = true;
    xd.resolveExternals = true;
    xd.load(strFile);

    // Return validation results in message to the user.
    if (xd.parseError.errorCode != 0)
    {
         return("Validation failed on " + strFile + 
                "\n=====================" +
                "\nReason: " + xd.parseError.reason + 
                "\nSource: " + xd.parseError.srcText + 
                "\nLine: " + xd.parseError.line + "\n");
    }
    else 
         return("Validation succeeded for " + strFile + 
                "\n======================\n" +
                xd.xml + "\n");
}