The XML schema language is the standard for verifying the XML document format. You can use XML schema in VB6 to verify the validity of XML.
This example demonstrates how to use Microsoft XML Parser 4.0 to verify XML files. First, create a file named wellformed. XSD and add the following code to it:
<? XML version = "1.0"?>
<Xs: schema targetnamespace = "http://tempuri.org/WellFormed.xsd"
Xmlns = "http://tempuri.org/WellFormed.xsd"
Xmlns: xs = "http://www.w3.org/2001/XMLSchema"
Attributeformdefault = "qualified"
Elementformdefault = "qualified">
<Xs: element name = "test">
<Xs: complextype>
<Xs: sequence>
<Xs: element name = "name" type = "XS: string" minoccurs = "0"/>
</Xs: sequence>
</Xs: complextype>
</Xs: Element>
</Xs: schema>
Create a file named wellformed. xml and add the following code to it:
<? XML version = "1.0" encoding = "UTF-8"?>
<Test xmlns = "http://tempuri.org/WellFormed.xsd">
<Name> John Doe </Name>
<Temp/>
</Test>
This XML file does not match the schema above. Therefore, an error occurs during verification.
To verify the XML document, you must create an instance of the xmlschemacache object. This object has an XML schema set. You can add content to the set by calling the add method and providing the schema namespace and its URL or file path. (The sample code looks for the file created above in the executable program path .)
Dim XMLSCHEMA as msxml2.xmlschemache40
Set XMLSCHEMA = new msxml2.xmlschemache40
XMLSCHEMA. Add "http://tempuri.org/WellFormed.xsd ",_
App. Path & "/wellformed. XSD"
Create and initialize an XML domdocument object instance. Xmlschemacache and domdocument are correlated:
Dim xmlmessage as msxml2.domdocument40
Dim lngerrcode as long
Set xmlmessage = new msxml2.domdocument40
Xmlmessage. async = false
Xmlmessage. validateonparse = true
Xmlmessage. resolveexternals = false
Set xmlmessage. schemas = XMLSCHEMA
After loading the XML document, call the validate method of domdocument. If the schema is inconsistent during the validation process, a parsing error occurs:
Call xmlmessage. Load (App. Path & "/wellformed. xml ")
Lngerrcode = xmlmessage. Validate ()
If xmlmessage. parseerror. errorcode <> 0 then
Text1.text = "Reason:" & xmlmessage. parseerror. Reason
End if
A parsing error occurs when parsing the wellformed. XML document. To correct this error, because the <temp/> label is deleted from the file.