Validating with Schema
Before we dive into the details of creating XSD schemas, lets understand how to
use them for validating XML documents. You’ll need to get a copy of
MSXML
4.0 and install it. Assuming you already have the schema and the XML document,
all you need now is a few lines of code to validate. I wrote a simple app that
validates and XML document using an XSD schema just to show you how to write the
code. You can
download it here.
You’ll first instantiate an XMLSchema object and add to it the XSD schema
file that you already have.
Dim schemaCache As MSXML2.XMLSchemaCache40
Set schemaCache = New MSXML2.XMLSchemaCache40
schemaCache.Add "","D:\schemas\mySchema.xsd"
When you call the Add method, the first parameter is the namespace that your
XML document uses. If your XML document does not use a namespace, you can just
pass an empty string like you see here (To learn more about XML namespaces, see
the XML Namespaces tutorial.). The second parameter is the URL or file path pointing
to the XSD schema document. Next, you create a DOM document and add to it the
schemaCache:
Dim doc As MSXML2.DOMDocument40
Set doc = New MSXML2.DOMDocument40
Set doc.schemas = schemaCache
Now you are ready to load the XML document and do the validation:
doc.async = False
If Not doc.Load("D:\docs\myDoc.xml") Then
MsgBox "Error loading XML document: " &
doc.parseError.reason
End If
After loading the document, you must check the parseError property for validation
errors. As you can see, validating is quite easy, once you have the XSD schema.
Now I’ll show you the basics for creating XSD schemas.