Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XML Schemas

Validate an XML Document Against an XML Schema Using Script

To validate an XML document file to an XML Schema definition language (XSD) schema file from within Windows script you use the schemaLocation attribute. The example below demonstrates this validation technique using the following three files:

To validate to XML Schema using Windows script

  1. Open Notepad
  2. Create the three files: doc.xml, doc.xsd, and validate.js.

    To create the files, copy each of the following samples and paste them to the Notepad window.Save them all in the same folder, using the names provided.

    doc.xml

    <?xml version="1.0"?>
    <x:doc  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
        xmlns:x='http://xsdtesting'
        xsi:schemaLocation='http://xsdtesting doc.xsd'>
       <x:notDeclared/>
    </x:doc>

    doc.xsd

    <?xml version="1.0"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
        targetNamespace = "http://xsdtesting"
        xmlns:x = "http://xsdtesting"
        elementFormDefault = "qualified">
       <xs:element name="doc"></xs:element>
    </xs:schema>

    validate.js

    var x = new ActiveXObject("MSXML2.DOMDocument.5.0");
    x.async = false;
    x.validateOnParse = true;
    x.resolveExternals = true;
    x.load("doc.xml");
    if (x.parseError.errorCode != 0) 
       {
         WScript.Echo("errorReason=" + x.parseError.reason); 
       }
    else 
         WScript.Echo("===NO PARSE ERROR===\n" + x.xml);
  3. Run the validate.js file.

    You should see the following alert text appear when you run the file.

    errorReason=The element 'x:notDeclared'is used but not declared in the DTD/schema.

    This indicates that the doc.xml file is not valid according to doc.xsd, because it contains an undeclared element.

  4. Try experimenting with different ways to resolve the parse error, and then run the script again.

    For example, you could remove the undeclared element by deleting the following line of text from the doc.xml file.

       <x:notDeclared/>

    Alternatively, you could declare the element in the doc.xsd file by adding the following lines directly before the </xs:schema> tag (the last line of the file).

    <xs:element name="notDeclared"></xs:element>

See Also

XML Schema Examples | XML Schema Element Map | XML Schema Elements | XML Data Types Reference | Primitive XML Data Types | Derived XML Data Types | Data Type Facets | IXMLDOMSchemaCollection/XMLSchemaCache

Other Resources Other Resources

World Wide Web Consortium (W3C) XML Schema Part 2: Datatypes | World Wide Web Consortium (W3C) XML Schema Part 1: Structures