I am using the following function to receive XML data from a URL.
Is there a more efficient method for retrieving this XML data?
Public Function UserLocation() As String
Try
Dim XML As Object = Server.CreateObject("MSXML2.DOMDocument.6.0")
Dim getXML As String = "<URL>"
XML.async = "false"
XML.resolveExternals = "false"
XML.setProperty("ServerHTTPRequest", True)
XML.Load(getXML)
Return XML.documentElement.SelectSingleNode("name").Text
Catch e As Exception
Return False
End Try
End Function
-
\$\begingroup\$ Welcome to Code Review! I hope you get some great answers. \$\endgroup\$Phrancis– Phrancis2016年08月22日 01:54:58 +00:00Commented Aug 22, 2016 at 1:54
-
\$\begingroup\$ as for me, it's an awful way to work with XML \$\endgroup\$Disappointed– Disappointed2016年08月22日 10:30:47 +00:00Commented Aug 22, 2016 at 10:30
-
\$\begingroup\$ What exactly do you mean by efficient? In terms of code size, this is already efficient. How can you ever return a boolean from a function that is declared to return a string? \$\endgroup\$Roland Illig– Roland Illig2017年07月03日 06:56:23 +00:00Commented Jul 3, 2017 at 6:56
1 Answer 1
I am giving code feedback based on c# however I think you can apply that to vb.
You can leverage the HttpWebRequest
class to extract the xml response.
public static XmlDocument MakeRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
return (xmlDoc);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.Read();
return null;
}
}
Then you can invoke the function with requested url which has xml response.
XmlDocument locationsResponse = MakeRequest(locationsRequest);
ProcessResponse(locationsResponse);
Now in the ProcessResponse
function you can extract the value from XmlDocument
using either XPath query or linq to xml.
static public void ProcessResponse(XmlDocument doc)
{
// Here you query the doc..
}