3
\$\begingroup\$

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
\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Review! I hope you get some great answers. \$\endgroup\$ Commented Aug 22, 2016 at 1:54
  • \$\begingroup\$ as for me, it's an awful way to work with XML \$\endgroup\$ Commented 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\$ Commented Jul 3, 2017 at 6:56

1 Answer 1

2
\$\begingroup\$

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.. 
 }
answered May 4, 2017 at 4:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.