GetXML Function – Send and Retrieve XML in ASP or VBScript

XML data sources are more and more important today. From RSS feeds to SOAP to eCommerce based applications. The ability to send and retrieve XML from a web application can be critical. Thankfully ASP has the ability to read from an HTTP data stream via a COM object from Microsoft called “ServerXMLHTTP” which facilitates the whole process.

Here are a couple of functions to send XML and then read the XML response from the web server. If you just want to read the XML from the remote machine simply pass a blank string as the sSendXML portion of the function will retrieve the default information. If you want to use this function in VBScript just remove the “Server.” potion of the “Set oXMLHTTP = Server.CreateObject(“MSXML2.ServerXMLHTTP”)” line.

After retrieving the XML from the remote server you’ll have to use the Split() function or more likely the Microsoft XML DOM object to parse the response.

Function GetXML(sSendXML, sURL)
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com
  Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
  oXMLHTTP.Open "POST",sURL,false
  oXMLHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

  On Error Resume Next
  oXMLHTTP.send sSendXML
  sXMLResponse = oXMLHTTP.responseText

  If Err.Number = 0 Then
    GetXML = sXMLResponse
  Else
    GetXML = XMLErrorHandeler
  End If
  On Error Goto 0

  Set oXMLHTTP = Nothing
End Function


Function XMLErrorHandeler
  'This script is provided under the Creative Commons license located
  'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
  'be used for commercial purposes with out the expressed written consent
  'of NateRice.com
  If Err.Number > 0 Then
    XMLErrorHandeler = "ERROR" & vbCRLF & _
                       "  ERR Number: " & Err.Number & vbCRLF & _
                       "  ERR Description: " & Err.Description
  Else
    XMLErrorHandeler = ""
  End If
End Function

 

Leave a Comment