如何使用vb.NET从URL读取XML数据并保存

时间:2009-10-16 06:57:15

标签: vb.net httprequest

朋友们,我能够通过单个字节获取XML文件,这可能会遇到一些问题。你可以建议我用另一种方法来保存XML文件吗?

  Try
        Dim strUrl As String = "http://example.com" 
        Dim wr As HttpWebRequest = CType(WebRequest.Create(strUrl), HttpWebRequest)
        Dim ws As HttpWebResponse = CType(wr.GetResponse(), HttpWebResponse)
        ws.ContentType = "UTF-16"
        Dim str As Stream = ws.GetResponseStream()
        Dim inBuf(100000) As Byte
        Dim bytesToRead As Integer = CInt(inBuf.Length)
        Dim bytesRead As Integer = 0
        While bytesToRead > 0
            Dim n As Integer = str.Read(inBuf, bytesRead, bytesToRead)
            If n = 0 Then
                Exit While
            End If
            bytesRead += n
            bytesToRead -= n
        End While
        Dim fstr As New FileStream("c:/GetXml.xml", FileMode.OpenOrCreate, FileAccess.Write)
        fstr.Write(inBuf, 0, bytesRead)
        str.Close()
        fstr.Close()
    Catch ex As WebException
        Response.Write(ex.Message)
    End Try

3 个答案:

答案 0 :(得分:6)

为什么不使用WebClient类及其DownloadFile方法?似乎更容易....

这是在C#中,但你应该没有把它转换为VB.NET:

WebClient wc = new WebClient();
wc.DownloadFile("http://xyz", @"C:\getxml.xml");

你已经完成了!

马克

答案 1 :(得分:0)

考虑使用XMLTextReader。这个例子只是将整个XML加载到一个字符串中,但显然你可以把它写成一个文件:

    Dim strUrl As String = "http://xyz.com"
    Dim reader As XmlTextReader = New XmlTextReader(strUrl)
    Dim output as String

    Do While (reader.Read())
        Select Case reader.NodeType
            Case XmlNodeType.Element 

                Output = Output + "<" + reader.Name

                If reader.HasAttributes Then 
                    While reader.MoveToNextAttribute()
                        Output = Output + " {0}='{1}'", reader.Name, reader.Value)
                    End While
                End If
                Output = Output + ">"
            Case XmlNodeType.Text
                Output = Output + reader.Value
            Case XmlNodeType.EndElement
                Output = Output + "</" + reader.Name + ">"
        End Select
    Loop

答案 2 :(得分:0)

如果服务将请求发送到我们的网址,该怎么办?如何调整它以读取他们发送的http流?有这么难的时间......(我应该做一个单独的线程吗?抱歉。)