用XSD校驗XML
由了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.xsd
用來校驗books.xml文件的Schema
books.xml
該文件將被載入并且和books.xsd對照校驗
Visual Basic校驗代碼
創建一個XMLSchemaCache對象,將schema添加給它,然后設置schemas property of the DOMDocument對象的shemas屬性。在開始的時候你要進行如下操作:
打開Visual Basic 6.0,選擇Standard EXE新項目
在Project菜單中選擇References.
在Available References列表中選擇Microsoft XML,v4.0
給Form1添加一個Command button
存儲該項目
books.xml
在XML編輯器甚至一般的文本編輯器中輸入以下XML代碼,并且存為books.xml:
<?xml version="1.0"?>
<x:catalog xmlns:x="urn:books">
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications with XML.</description>
<title>2000-10-01</title>
</book>
</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"/>
</xsd:sequence>
</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"/>
</xsd:sequence>
<xsd:attribute name="id" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Visual Basic校驗代碼
你可以運行下面的例子:
拷貝下面的代碼到Command1_Click過程中
Private Sub Command1_Click()
Dim xmlschema As MSXML2.XMLSchemaCache
Set xmlschema = New MSXML2.XMLSchemaCache
xmlschema.Add "urn:books", App.Path & "\books.xsd"
Dim xmldom As MSXML2.DOMDocument
Set xmldom = New MSXML2.DOMDocument
Set xmldom.schemas = xmlschema
xmldom.async = False
xmldom.Load App.Path & "\books.xml"
If xmldom.parseError.errorCode <> 0 Then
MsgBox xmldom.parseError.errorCode & " " & xmldom.parseError.reason
Else
MsgBox "No Error"
End If
End Sub
執行該程序,然后點擊Command1按鈕,將返回"No Errors"消息框。
轉載:http://www.xfbbs.com/ArticleShow/43/Article_Show_25431.html