Visual Basic Code (errorXPath.frm)
' Check "Microsoft XML, v50" from Project->References... ' in Visual Studio. Set xd = CreateObject("MSXML2.DOMDocument.5.0") Set xs = CreateObject("MSXML2.XMLSchemaCache.5.0") ' Add xs to xd. xs.Add "urn:books", App.Path & "\books.xsd" Set xd.schemas = xs xd.async = False xd.validateOnParse = False xd.Load App.Path & "\books.xml" msg = "Validating DOM..." & vbCrLf Set er1 = xd.Validate If er1.errorCode <> 0 Then msg = msg & "invalid dom:" & vbCrLf & er1.reason _ & "errorXPath:" & vbCrLf & er1.errorXPath & vbCrLf Else msg = msg & "DOM is valid:" & vbCrLf & xd.xml & vbCrLf End If msg = msg & vbCrLf & "Validating nodes..." & vbCrLf Set nlist = xd.selectNodes("//book") For Each node In nlist Set er1 = xd.validateNode(node) If er1.errorCode <> 0 Then msg = msg & vbCrLf & "Node is invalid:" & vbCrLf & er1.reason _ & "errorXPath:" & vbCrLf & er1.errorXPath _ & vbCrLf Else msg = msg & vbCrLf & "Node is valid:" & vbCrLf & node.xml & vbCrLf End If Next MsgBox msg
Try It!
- Copy the XML data (books.xml), and paste it into a text file. Save the file as books.xml.
- Copy the XSD listing (books.xsd), and paste it into a text file. Save the file as books.xsd, in the same directory where you saved books.xml.
- Create a Standard EXE project in Visual Basic. Save the empty project as errorXPath.vbp to the same directory where you saved books.xml and books.xsd. Name the form file errorXPath.frm.
- Create a reference to MSXML 5.0. To do this, select References... from the Project menu, then check the box for Microsoft XML, v50.
- Copy the Visual Basic code listing above, and paste it into the form_load subroutine.
- Execute the code by selecting Start from the Run menu.
- Verify that your output is the same as that listed in Output for the errorXPath Example.