2

朋友们,我可以通过唱字节来获取 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
4

3 回答 3

7

为什么不只使用WebClient类及其DownloadFile方法?好像轻松了很多......

这是在 C# 中,但您应该可以轻松地将其转换为 VB.NET:

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

你就完成了!

马克

于 2009-10-16T08:03:03.020 回答
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
于 2009-10-16T07:48:46.887 回答
0

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

于 2013-02-22T21:46:09.240 回答