Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing XML String in VBScript

I have a web service which returns XML string similar to the one below:

<?xml version="1.0"?>
<Result>
    <PersonID>991166187</PersonID>
    <AddressID>1303836</AddressID>
</Result>

I need a VBScript code that will allow me to retrieve the values for PersonID and AddressID. My specific question is how can I retrieve value for PersonID, i.e. 991166187, from the XML string in my original post.

In terms of what I have tried, I have the following code:

Dim doc
Dim xmlString
Dim nodes
Dim idArray

xmlString = "<?xml version="1.0"?><Result><PersonID>991166187</PersonID><AddressID>1303836</Address&#8204;&#8203;ID></Result>"

Set doc = CreateObject("MSXML2.DOMDocument")
doc.loadXML(xmlString)

'Set nodes = doc.selectNodes("Result/PersonID/AddressID")
nodes = doc.getElementsByTagName("PersonID")

For Each node In nodes
  WScript.Echo "Person ID: " & node.text
like image 654
Babs Avatar asked Oct 17 '15 13:10

Babs


1 Answers

Went through your code and there were a couple of things you need to edit:

  1. The XML string you get has double quotes in it. You cannot directly use those double quotes and save it into a string. You have two options here:
    1. create an XML file from the string and parse
    2. replace the double quotes with single quotes using Replace
  2. The getElementsByTagName line should have a Set in it, since the value returned is an object.

Used this code on my machine and it retrieved the desired output:

Dim doc 
Dim xmlString 
Dim nodes
xmlString = "<?xml version='1.0'?><Result><PersonID>991166187</PersonID><AddressID>1303836</AddressID></Result>"

Set doc = CreateObject("MSXML2.DOMDocument") 
doc.loadXML(xmlString) 
Set nodes = doc.getElementsByTagName("PersonID")

For Each node In nodes
  MsgBox "Person ID: " & node.text
Next
MsgBox "done"
like image 109
schizovivek Avatar answered Oct 21 '22 03:10

schizovivek