如何使用vb.NET从URL读取XML数据并保存
问题描述:
朋友们,我可以通过单字节获取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
答
为什么不直接使用WebClient
类及其DownloadFile
方法?似乎轻松了很多....
这是在C#中,但你应该没有问题,转换,为VB.NET:
WebClient wc = new WebClient();
wc.DownloadFile("http://xyz", @"C:\getxml.xml");
就大功告成了!
Marc
答
考虑使用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
答
如果服务将请求发送到我们的URL,该怎么办?我该如何调整以读取它们发送的http流?有这么难的时候...(我应该做一个单独的线程吗?对不起。)