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:
- doc.xml: The XML file to be validated.
- doc.xsd: The XML Schema file against which doc.xml will be validated. This file is referenced in doc.xml with the schemaLocation attribute.
- validate.js: A Windows script file used to perform the validation and return the results as an alert message.
To validate to XML Schema using Windows script
- Open Notepad
- 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);
- 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.
- 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
World Wide Web Consortium (W3C) XML Schema Part 2: Datatypes | World Wide Web Consortium (W3C) XML Schema Part 1: Structures