JScript Code (validateNode.js)

 

[This sample code uses features that were implemented only in MSXML 6.0.]

var xs, xd;

main();

function main() 
{
  try {
    xs = new ActiveXObject("MSXML2.XMLSchemaCache.6.0");
    xd = new ActiveXObject("MSXML2.DOMDocument.6.0");
  }
  catch (e) {
    WScript.Echo("Mirosoft XML Core Services (MSXML) 6.0 is not installed.\n"
          +"Download and install MSXML 6.0 from https://msdn.microsoft.com/xml\n"
          +"before continuing.");
    return;
  }

  try {
    xs.add("urn:books", "validateNode.xsd");
    xd.schemas = xs;
    xd.async = false;
    xd.validateOnParse = false;
  }
  catch (e) {
    WScript.Echo("Failed to add to schema cache: "+e.description);
    return;
  }

  try {
    xd.load("validateNode.xml");
  }
  catch (e) {
    WScript.Echo("can't load validateNode.xml : " + e.description);
    return;
  }

  var err = xd.validate();
  if (err.errorCode != 0 ) 
    WScript.Echo("invalid dom: \n" + err.reason);
  else
    WScript.Echo("dom is valid:\n" + xd.xml);

  var nlist = xd.selectNodes("//book");
  for (var node = nlist.nextNode(); node!=null; node=nlist.nextNode())
  {
    var err = xd.validateNode(node);

    if (err.errorCode != 0) 
      WScript.Echo("invalid node:\n" + err.reason);
    else
      WScript.Echo(node.xml);
  }

}

Try It!

  1. Copy the XML data (validateNode.xml), and paste it into a text file. Save the file as validateNode.xml.

  2. Copy the XSD listing (validateNode.xsd), and paste it into a text file. Save the file as validateNode.xsd, in the same directory where you saved validateNode.xml.

  3. Copy the JScript listing above, and paste it into a text file. Save the file as validateNode.js, in the same directory where you saved validateNode.xml and validateNode.xsd.

  4. Double click the validateNode.js file from Windows Explorer to launch the application. Alternatively, you can type "validateNode.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.

  5. Verify that your output is the same as that listed in Output for the validateNode Example.