Search code examples
vbscriptxml-parsingrandom-access

Choosing a random XML node in VBscript


I have been having trouble figuring out how to choose a random xml node and store its text value into a variable. I will be using the script in multiple instances and it will need to work regardless of the XML length. The XML file is formatted like this:

<?xml version="1.0" encoding="utf-8" ?>
    <file>file path 1</file>
    <file>file path 2</file>
    <file>file path 3</file>

The code I have written is as follows:

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.load("xmlfilepath") 
x=xmlDoc.getElementsByTagName("file")
max = x.length
min=0
temp=(Int((max-min+1)*Rnd+min))
file = x[temp].nodeText

'do some things with the file path stored in the file variable.

I know I am doing something wrong but I have no idea what.

Thanks in advance for any help you guys can give me.

EDIT: I am getting an error on line 7 char 9. expected end of statement.

As for the "title" I didn't notice it was like that when I copied it overhere. In my code it is "file". I also fixed it in this edit. but that wasn't part of my issue.


Solution

  • In next script, comments '#1..'#6 explain steps to debug your original code. All (debug only) Wscript.Echo statements could be removed.

    ' VB Script Document: launch under cscript
    option explicit
    On Error Goto 0
    
    Dim xmlDoc, x, max, min, file, temp, xLoad
    
    '#5 Initialize the random-number generator
    ' otherwise Rnd function keeps return the same only value 
    randomize
    
    Set xmlDoc = CreateObject("Microsoft.XMLDOM")
    
    '#1 ensure loading the document
    xLoad = xmlDoc.load("D:\VB_scripts\SO\files_In\29285755.xml")
    Wscript.Echo "parseError.errorCode " & xmlDoc.parseError.errorCode
    If xLoad Then
        '#3 invalid property assignment
        ' x=xmlDoc.getElementsByTagName("file")
        set x=xmlDoc.getElementsByTagName("file")
        ' or   '     set x = xmlDoc.documentElement.selectNodes("/title/file")
        max = x.length
        min=0
    
        '#6  Object required: '[object]' error in line: file = x(temp).Text
        ' i.e. index out of bounds and zero based indexing and temp >= max 
        ' temp=(Int((max-min+1)*Rnd+min))
        temp=(Int((max-min)*Rnd+min))
        Wscript.Echo "max", max, "temp", temp, "temp>=max", CStr(temp >= max)
    
        '#4 Object doesn't support this property or method: 'nodeText'
        ' file = x(temp).nodeText
        file = x(temp).Text
    Else
        '#2 descramble and resolve error in loading the document 
        ' parseError.errorCode -1072896683
        ' parseError.reason Only one top level element is allowed in an XML document
        ' i.e. the root element missing: added <title> 
        Wscript.Echo "parseError.reason " & xmlDoc.parseError.reason
        file = "N/A"
    End If
    Wscript.Echo file