2011-08-29 50 views
0

我正在嘗試使用XmlRead設置用戶代理的請求。我搜索了很多關於這個,並找不到答案。這裏是我的代碼塊:Visual Basic使用ReadXml設置用戶代理

Dim RssData As DataSet 
     Dim Title As String 
     Dim Url As String 
     Dim Stream As String 
     Dim buffer As Integer 
     RssData = New DataSet() 
     RssData.ReadXml("http://localhost/user_agent.php") 
     buffer = 0 
     For Each RssRow As DataRow In RssData.Tables("entry").Rows 
      Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30) 
      Stream += Title & vbCrLf 

     Next 
     LinkLabel3.Text = Stream 

     For Each RssRow As DataRow In RssData.Tables("entry").Rows 
      Title = Microsoft.VisualBasic.Left(RssRow.Item("title").ToString, 30) 
      Url = RssRow.Item("url").ToString 
      LinkLabel3.Links.Add(buffer, Title.Length, Url) 
      buffer = buffer + Title.Length + 2 
     Next 

回答

1

實際執行Web請求的代碼的一部分埋入相當深,所以你不得不繼承一串代碼,做你問什麼。相反,讓我建議一個不同的路徑,使用易於設置標題的代碼自行下載XML,然後將其加載到數據集中。 WebClient類可讓您設置任意標題並具有簡單的DownloadString方法。一旦你有了,你可以把它包裝在一個MemoryStream並將其傳遞到ReadXml()。 (我無法找到一個方法來讀取XML作爲一個字符串,這就是爲什麼我不得不把它讀作Stream。)

''//Will hold our downloaded XML 
    Dim MyXml As String 

    ''//Create a webclient to download our XML 
    Using WC As New System.Net.WebClient() 
     ''//Manually set the user agent header 
     WC.Headers.Add("user-agent", "your user agent here") 
     ''//Download the XML 
     MyXml = WC.DownloadString("http://localhost/user_agent.php") 
    End Using 
    ''//Create our dataset object 
    Dim RssData As New DataSet() 
    ''//There is no direct method to load XML as a string (at least that I could find) so we will 
    ''// convert it to a byte array and load it into a memory stream 
    Dim Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(MyXml) 
    Using MS As New System.IO.MemoryStream(Bytes) 
     ''//Load the stream into the reader 
     RssData.ReadXml(MS) 
    End Using 

    ''//Your code continues normally here 
+0

非常感謝,這個工作。我聽說ReadXml不是完成這項工作的最佳方式,但是使用其他方式我無法將它們設置爲DataSet()。再次感謝。 – BebliucGeorge