2010-09-21 11 views

Répondre

4

Vous pouvez utiliser WebRequest pour extraire le code XML du site distant; alors vous pouvez analyser le contenu dans un objet XmlDocument.

 
' Create a WebRequest to the remote site 
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://www.domain.com/fetch.xml") 

' NB! Use the following line ONLY if the website is protected 
request.Credentials = New System.Net.NetworkCredential("username", "password") 

' Call the remote site, and parse the data in a response object 
Dim response As System.Net.HttpWebResponse = request.GetResponse() 

' Check if the response is OK (status code 200) 
If response.StatusCode = System.Net.HttpStatusCode.OK Then 

    ' Parse the contents from the response to a stream object 
    Dim stream As System.IO.Stream = response.GetResponseStream() 
    ' Create a reader for the stream object 
    Dim reader As New System.IO.StreamReader(stream) 
    ' Read from the stream object using the reader, put the contents in a string 
    Dim contents As String = reader.ReadToEnd() 
    ' Create a new, empty XML document 
    Dim document As New System.Xml.XmlDocument() 

    ' Load the contents into the XML document 
    document.LoadXml(contents) 

    ' Now you have a XmlDocument object that contains the XML from the remote site, you can 
    ' use the objects and methods in the System.Xml namespace to read the document 

Else 
    ' If the call to the remote site fails, you'll have to handle this. There can be many reasons, ie. the 
    ' remote site does not respond (code 404) or your username and password were incorrect (code 401) 
    ' 
    ' See the codes in the System.Net.HttpStatusCode enumerator 

    Throw New Exception("Could not retrieve document from the URL, response code: " & response.StatusCode) 

End If 
+0

'GetResponse' n'est pas un membre de 'System.Net.HttpWebRequest'. –

+0

@ScottBeeson Dans quel langage de programmation? Pour .NET, System.Net.HttpWebRequest.GetResponse() existe depuis la version 1.1, voir http://msdn.microsoft.com/fr-fr/library/system.net.httpwebrequest.getresponse(v=vs.71) .aspx – KBoek

+0

vb.net 4.5, Visual Studio 2012 –

2

Avec ce Skeet a dit qu'il y @ Jon a aussi intégré dans WebClient:

Dim MyData As String 
    Try 
     Using WC As New System.Net.WebClient() 
      MyData = WC.DownloadString("http://www.example.com/text.xml") 
     End Using 
    Catch ex As Exception 
     'Error downloading 
    End Try 
Questions connexes