I'm trying to make use of the Wikipedia API for a simple school project. I'm trying to parse this URL using WebRequest to download the source and XElement to parse the data. I'm using the following code
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
but I'm getting NullReferenceException at the beginning of For Each. Is this the right way to parse XML document in vbNET?
Try this
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
This can probably be simplified using LINQ, but it is a start.