I’ve got a function api_request which takes API method as an argument, and returns XMLTextReader
Shared Function api_request(method As String) As XmlTextReader
request_text = method & ".xml"
url = "https://api.vk.com/method/" & request_text & "&access_token=" & token
Return New XmlTextReader(url)
End Function
I call this function from different places to make request to site API and depending on the method results are parsed very differently.
So in each method I have something like this:
Dim s As Xml.XmlReader = api_request("users.get")
While s.Read
If s.NodeType = XmlNodeType.Element Then
If s.Name = "user" Then
curr_user=s.ReadElementContentAsString
ElseIf s.Name = "error" Then
error_handler(s, "user.get")
End If
End If
End While
As you may see, I have the code ElseIf s.Name = "error" Then error_handler(s, "user.get"). This is because when error happens, server always returns something like this:
<error>
<error_code>4</error_code>
<error_msg>Incorrect signature</error_msg>
</error>
This is parsed in error_handler Sub, and depending on the error following actions are chosen.
This code works, but I have to check if I encounter error like that ElseIf s.Name = "error" every time, though all the methods call the api_request function. Is it possible to check for error in api_request function before returning the Reader? The problem is if I start reading xml there, and there isn’t an error, I can’t anyhow position the Reader to the start.
Since you can’t change your position with an
XmlTextReader, the only other solution would be to load the entire XML document into memory. Presumably theXmlTextReaderis going to download the entire XML file into memory when it first reads it anyway, so any performance hit should be negligible. I would suggest something like this:And then in the method that calls
api_request, do something like this: