Share via


Visual Basic Code (schemaCache.frm)

 

This topic provides Visual Basic 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. Create a Standard EXE project in Visual Basic. Save the empty project as schemaCache.vbp to the same directory you used in previous steps. Name and save the form file as schemaCache.frm.

  5. Create a reference to MSXML 6.0. To do this, select References... from the Project menu, and then check the box for Microsoft XML, v6.0.

  6. Copy the Visual Basic code listing above, and paste it into the Visual Basic code editor to replace whatever code is already there.

  7. Execute the code by selecting Start from the Run menu.

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

schemaCache.frm

Private Sub Form_Load()
    Dim sOutput As String
    sOutput = ValidateFile("sc-valid.xml", "urn:books", "sc.xsd")
    sOutput = sOutput & ValidateFile("sc-notValid.xml", "urn:books", _
                                      "sc.xsd")
    MsgBox sOutput
    Unload Me
End Sub

Function ValidateFile(strXmlFile As String, strUrn As String, _
                        strXsdFile As String)
    
   ' Create a schema cache and add books.xsd to it.
   Dim xs As New MSXML2.XMLSchemaCache60
   xs.Add strUrn, App.Path & "\" & strXsdFile

   ' Create an XML DOMDocument object.
   Dim xd As New MSXML2.DOMDocument60

   ' Assign the schema cache to the DOM document.
   ' schemas collection.
   Set xd.schemas = xs

   ' Load books.xml as the DOM document.
   xd.async = False
   xd.Load App.Path & "\" & strXmlFile

   ' Return validation results in message to the user.
   If xd.parseError.errorCode <> 0 Then
        ValidateFile = "Validation failed on " & _
             strXmlFile & vbCrLf & _
             "=====================" & vbCrLf & _
             "Reason: " & xd.parseError.reason & _
             vbCrLf & "Source: " & _
             xd.parseError.srcText & _
             vbCrLf & "Line: " & _
             xd.parseError.Line & vbCrLf
    Else
        ValidateFile = "Validation succeeded for " & _
             strXmlFile & vbCrLf & _
             "======================" & _
             vbCrLf & xd.xml & vbCrLf
    End If
End Function