-3

I am using the below function to load xml and then return the array with values. But when i call it in another function it gives error "arrXML is undefined".

function readXML() {
     // create an array object
     var arrXML = new Array();

     //create XML DOM object
     var docXML = Sys.OleObject("Msxml2.DOMDocument.6.0");

     // load xml
     docXML.load("C:\\Users\\ankit\\Desktop\\read.xml");

     // search nodes with 'config' tag
     var Nodes = docXML.selectNodes("//config");
     for (i = 0; i < Nodes.length; i++){
         var ChildNodes = Nodes.item(i);
         arrXML[i] = Nodes(i).childNodes(0).text +":"+Nodes(i).childNodes(1).text;
     }
     // return array of XML elements
     return arrXML; 
}

function getvalues() {
    log.message(arrXML[1]);  // this line gives error
}
vinu
  • 191
  • 2
  • 7
  • 22
  • You are not checking to make sure that the document loaded correctly or that any of your variables ended up with data in them. – BSMP Jun 09 '15 at 04:27
  • The doc is getting loaded successfully . if you print like log.message(readXML()[1]) , it prints the values in another function. but i do not want to call it like this. It should be directly called – vinu Jun 09 '15 at 04:30
  • 2
    `arrXML` is local to `readXML` because you declared it with `var` inside that block. `getValues` has no idea it exists (because it no longer does) – Gary Jun 09 '15 at 04:32
  • Yes Gary , you are right, I took out var and now its printing the values . Thanks a lot. – vinu Jun 09 '15 at 04:37
  • 1
    Alternatively you could make arrXML global or pass it to whatever functions need to use it. – Gary Jun 09 '15 at 05:07

1 Answers1

0

arrXML is local to the function readXML because you declared it with the var keyword inside that block. getValues has no idea it exists (because it no longer does).

Your options are to make the variable global (which you should be careful with)

vinu = {}; // vinu is global namespace containing the array
function readXML() {
  vinu.arrXML = [];
  // ...
  return vinu.arrXML; // This might not even be necessary in this case
}

function getvalues() {
  log.message(vinu.arrXML[1]);
}

... or to pass the variable to the function when you call it.

function getvalues(arg) {
  log.message(arg[arrXML[1]]);
  return arg; // This function can't change the original variable, so use the return if need-be
}

// Somewhere that has access to the actual "arrXML"
getvalues(arrXML);

... or use a closure.

Gary
  • 13,303
  • 18
  • 49
  • 71