由了XML Schema,你可以用来校验XML文档的语义和结构。在MSXML 4.0技术预览版本已经提供了用XSD Schema来校验XML文档的功能。在校验文档时,将schema添加到XMLSchemaCache对象中,设置其 object, set the schemas property of a DOMDocument对象的schemas属性引用XMLSchemaCache对象中的schema。在将XML文档载入到DOMDocument对象中时将自动执行校验操作。我们不妨用例子来说明如何在Visual Basic中通过编程实现XML文档校验。其中包括:
books.xml
在XML编辑器甚至一般的文本编辑器中输入以下XML代码,并且存为books.xml:
< ?xml version="1.0"?>
< x:catalog xmlns:x="urn:books">
< book id="bk101">
< author>Gambardella,
Matthew</< font>author>
< title>XML Developer's Guide</<
font>title>
< genre>Computer</<
font>genre>
< price>44.95</< font>price>
< publish_date>2000-10-01</<
font>publish_date>
< description>An in-depth
look at creating applications with XML.</< font>description>
< title>2000-10-01</<
font>title>
</< font>book>
</< font>x:catalog>
books.xsd
下面是本例中使用的books.xsd schema。
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
< xsd:element name="catalog"
type="CatalogData"/>
< xsd:complexType name="CatalogData">
< xsd:sequence>
< xsd:element name="book"
type="bookdata"
minOccurs="0"
maxOccurs="unbounded"/>
</< font>xsd:sequence>
</< font>xsd:complexType>
< xsd:complexType name="bookdata">
< xsd:sequence>
< xsd:element name="author"
type="xsd:string"/>
< xsd:element name="title"
type="xsd:string"/>
< xsd:element name="genre"
type="xsd:string"/>
< xsd:element name="price"
type="xsd:float"/>
< xsd:element name="publish_date"
type="xsd:date"/>
< xsd:element name="description"
type="xsd:string"/>
</< font>xsd:sequence>
< xsd:attribute name="id"
type="xsd:string"/>
</< font></xsd:complexType>
</< font></xsd:schema>
Visual Basic校验代码
你可以运行下面的例子:
Private Sub Command1_Click()
Dim xmlschema As MSXML2.XMLSchemaCache
Set xmlschema = New MSXML2.XMLSchemaCache
xmlschema.Add "urn:books", App.Path & "ooks.xsd"
Dim xmldom As MSXML2.DOMDocument
Set xmldom = New MSXML2.DOMDocument
Set xmldom.schemas = xmlschema
xmldom.async = False
xmldom.Load App.Path & "ooks.xml"
If xmldom.parseError.errorCode <> 0 Then
MsgBox xmldom.parseError.errorCode & " " & xmldom.parseError.reason
Else
MsgBox "No Error"
End If
End Sub