how to parse xml in from a WinHttp.WinHttpRequest object?

7.3k views Asked by At

I have a standalone VBScript which connects to server and gets the response text(as XML) in a WinHttpRequest object. Now, my question is how do I parse the XML content in it. When I post a request(strPostData) I need to parse the response XML. What I am using below is not working as I'm unable to print output on the console. I'm able to output the ResponseText though. But I'm unable to parse it.

  Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5.1")
  objWinHttp.Send(strPostData)
  objWinHttp.WaitForResponse()

    If objWinHttp.Status = "200" Then
        GetDataFromURL = objWinHttp.ResponseText
        Set xmlDoc = CreateObject("Microsoft.XMLDOM")
        xmlDoc.loadXML(GetDataFromURL)
        Set ops = xmlDoc.getElementsByTagName("Response\Status").item(0).text


      WScript.Echo "Output is: " & ops
      WScript.Echo "Message: " & GetDataFromURL
      Msgbox GeteDataFromURL
      WScript.Quit(0)   

Here is the XML to be parsed:

<RCTRequest>
    <Response>
       <Name>aaa</Name>
       <Status>44</Status>
    </Response>
</RCTRequest>
4

There are 4 answers

0
RRUZ On

You can use XPath

  Set xmlDoc = CreateObject("Microsoft.XMLDOM")
  xmlDoc.async = false
  xmlDoc.SetProperty "SelectionLanguage", "XPath"      
  xmlDoc.loadXML(GetDataFromURL)
  Set ops =xmlDoc.SelectSingleNode("/RCTRequest/Response/Status")
  WScript.Echo "Output is: " &  (ops.text)
  WScript.Echo "Message: " & GetDataFromURL
  Msgbox GeteDataFromURL
  WScript.Quit(0)   
3
MBu On

I suppose you get "runtime error: Object required" error. It is caused by the line

Set ops = xmlDoc.getElementsByTagName("Response\Status").item(0).text

Just remove set from the beginning of that line.

0
Nilpo On

You're on the right track using XMLDOM. Check out my article Reading XML Files in WSH for examples on how to parse specific data from an XML input.

0
Rohith Ragav On
strFile = "inp.xml"
Set objFS = CreateObject( "Scripting.FileSystemObject" )
set xmlDoc=CreateObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load(strFile)
For each x in xmlDoc.documentElement.attributes
  WScript.Echo x.nodeName, x.text
Next

set xmlCol = xmlDoc.documentElement.childNodes
For Each Elem In xmlCol 
 If StrComp(Elem.nodeName, "p") = 0 Then
  set nestedChild = Elem.childNodes

  For Each node In nestedChild 
    If StrComp(node.nodeName, "XYZ") = 0 Then
      WScript.Echo Elem.xml
      set a = objFS.CreateTextFile("testfile.txt", true)
      a.WriteLine(Elem.xml)
      a.Close()
    End If
  Next

 End If
Next