2009-10-16 123 views
2

朋友們,我可以通過單字節獲取XML文件,也許這是一個問題。你可以建議我採用替代方法來做同樣的事情來保存XML文件嗎?如何使用vb.NET從URL讀取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 

回答

6

爲什麼不直接使用WebClient類及其DownloadFile方法?似乎輕鬆了很多....

這是在C#中,但你應該沒有問題,轉換,爲VB.NET:

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

就大功告成了!

Marc

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 
0

如果服務將請求發送到我們的URL,該怎麼辦?我該如何調整以讀取它們發送的http流?有這麼難的時候...(我應該做一個單獨的線程嗎?對不起。)