如何从vb.net中的远程URL读取xml

时间:2010-09-21 06:11:48

标签: vb.net

我在一个项目中工作,我想从远程网址读取一些数据,任何人都可以帮助我如何做这个功能

4 个答案:

答案 0 :(得分:6)

您可以使用WebRequest从远程站点检索XML;然后你可以将内容解析为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

答案 1 :(得分:2)

除了@Jon Skeet所说的还有内置的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

答案 2 :(得分:1)

您是否尝试过使用XDocument.LoadXmlDocument.Load

如果那些不符合您的要求,请提供更多详细信息。

答案 3 :(得分:0)

试试这个

http://www.codeproject.com/Tips/992109/Parsing-Reading-XML-from-URL-in-VB-NET

它提供了一些有用的例子。希望这会有所帮助...