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

标签 vb.net

我在一个项目中工作,因为我想从远程 url 读取一些数据,任何人都可以帮助我如何执行此功能

最佳答案

您可以使用 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

关于vb.net - 如何从 vb.net 中的远程 url 读取 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3757731/

相关文章:

.net - 如何将对象列表转换为对象在 VB.net 中实现的接口(interface)列表?

vb.net - 哪个更快? ByVal 还是 ByRef?

vb.net - 在面向对象编程中使用 .txt 文件的正确方法

vb.net - 将 jpg 转换为 avi vb.net

mysql - 如何过滤 3 个相关的 datagridview

c# - 带有 Windows API 代码包的 Windows XP 上的 EntryPointNotFoundException

vb.net:在 XML 注释中使用 <see> 标签

vb.net - 通过变量名访问 VB.Net 结构元素

vb.net - 我如何获得 Oracle.DataAccess.Client?

vb.net - VB.NET 中的运算符重载