共用方式為


Visual Basic XSD 擴充函式程式碼

下列程式碼片段顯示如何使用 XSD 擴充函式,根據節點的 XSD 資料型別傳回該節點。 這段範例程式碼是使用 type-is 函式傳回文件的第一個字串資料型別,並使用 type-local-name 函式傳回字串資料型別的節點清單。

Visual Basic 程式碼會建立 XMLSchemaCache60 物件、將命名空間 URI 宣告 (urn:books) 和結構描述 (books.xsd) 加入至物件,然後使用 DOMDocument 物件的 schemas 屬性參考結構描述。 請注意,程式碼中的 SelectionLanguage 屬性是設定為 XPath 而 SelectionNamespaces 屬性是設定為 "xmlns:ms='urn:schemas-microsoft-com:xslt",目的是要使用 ms: 命名空間前置詞。 將 books.xml 檔案載入 DOMDocument 物件時,驗證便會執行。 並且還會使用 DOMDocument 物件的 parseError 屬性傳回驗證錯誤。

執行範例

  1. 將下面所示的程式碼複製到 Command1_Click 程序。 完成後,您看到的程式碼應該類似以下的程式碼片段。

  2. 在 Visual Basic 工具列上,按一下 [開始],再按 [form1] 上的 [Command1] 按鈕。

執行範例時,Set objNodeList = xmldom.selectNodes "//*[ms:type-is('http://www.w3.org/2001/XMLSchema','string')]") 陳述式將傳回資料型別為 String 的節點清單。 For/Next 迴圈會逐一檢查節點,並在訊息方塊中顯示每個節點的文字。

Private Sub Command1_Click()
Dim xmlschema As Msxml2.XMLSchemaCache60
Set xmlschema = New Msxml2.XMLSchemaCache60
Dim xmldom As Msxml2.DOMDocument60
Set xmldom = New Msxml2.DOMDocument60
Dim objElem As IXMLDOMNode
Dim objNodeList As IXMLDOMNodeList

xmlschema.Add "urn:books", App.Path & "\books.xsd"
Set xmldom.schemas = xmlschema

xmldom.setProperty "SelectionLanguage", "XPath"
xmldom.setProperty "SelectionNamespaces", "xmlns:ms='urn:schemas-microsoft-com:xslt'"

xmldom.async = False
xmldom.Load App.Path & "\books.xml"

'returns a list of nodes with the string data type
Set objNodeList = xmldom.selectNodes _
    ("//*[ms:type-is('http://www.w3.org/2001/XMLSchema','string')]")
For i = 0 To (objNodeList.length - 1)
    MsgBox objNodeList.Item(i).Text
Next

If xmldom.parseError.errorCode <> 0 Then
    MsgBox xmldom.parseError.errorCode & " " & xmldom.parseError.reason
Else
    MsgBox "No Error"
End If

End Sub