我正在尝试使用维基百科 API 来完成一个简单的学校项目。我正在尝试使用 WebRequest
下载源代码并使用
XElement
解析数据。我正在使用以下代码Dim request As WebRequest = WebRequest.Create("http://bg.wikipedia.org/w/api.php?action=opensearch&format=xml&search=" + text)
request.Credentials = CredentialCache.DefaultCredentials
Dim reader As New StreamReader(request.GetResponse().GetResponseStream())
Dim elm As XElement = XElement.Load(reader)
If elm IsNot Nothing Then
Dim a As XElement = elm.Element("Section")
For Each page As Object In a.Elements("Item")
Dim title = page.Element("Text").Value
Dim url = page.Element("image").Value
Next
End If
但我在
NullReferenceException
开头得到了
For Each
。这是在 vbNET 中解析 XML 文档的正确方法吗? If elm IsNot Nothing Then
For Each xe As XElement In elm.Nodes
If xe.Name.LocalName = "Section" Then
For Each sxe As XElement In xe.Nodes
If sxe.Name.LocalName = "Item" Then
Dim title As String
Dim url As String
For Each n As XElement In sxe.Nodes
If n.Name.LocalName = "Text" Then
title = n.Value.ToString
ElseIf n.Name.LocalName = "Image" Then
url = n.@source
End If
Next
Debug.WriteLine(title)
Debug.WriteLine(url)
End If
Next
End If
Next
End If
这可能可以使用 LINQ 来简化,但这只是一个开始。