2008年8月27日星期三

Visual Basic load XML

Loading XML Content With Visual Basic

The load method allows you to open an XML source from either a file or a URL. The following example reads an XML file called cd.xml that resides on Juicy Studio. 

The async Property determines whether control is passed back to the application before it's loaded. The defualt value is True, in which case you can use the readyState Property to determine if it's finished loading. By setting it to False, control is passed back to Visual Basic when the document has completed loading.

To try this example, start a new project and add a CommandButton and a TextBox. Set the TextBox Properties, Name to txtXML, MultiLine to True, and ScrollBars to Both. 

Then add the following code to the CommandButton (in this example, called cmdLoad). 

Private Sub cmdLoad_Click() 
Dim xmlDoc As New DOMDocument
Dim xmlRootElement As IXMLDOMElement
Dim xmlError As IXMLDOMParseError
Dim success As Boolean
' Allow the document to complete loading
xmlDoc.async = False 
' Validate the document against a DTD 
xmlDoc.validateOnParse = True
success = xmlDoc.Load("http://www.juicystudio.com/tutorial/xml/cd.xml")
If success = True Then
Set xmlRootElement = xmlDoc.documentElement
txtXML.Text = xmlRootElement.xml
Set xmlRootElement = Nothing
Else
Set xmlError = xmlDoc.parseError
txtXML.Text = "Error code: " & xmlError.errorCode & vbCrLf _
& "Reason: " & xmlError.reason & vbCrLf _
& "Source: " & vbCrLf & xmlError.srcText & vbCrLf _
& "URL: " & xmlError.url
Set xmlError = Nothing
End If
End Sub

没有评论: