XML NodeList Java object showing null in Nashorn Javascript

207 Views Asked by At

I'm trying to read multiple matching values of an xpath expression from an xml file in an array in Nashorn Javascript. I'm using javax.xml.xpath classes inside Nashorn to parse xml data. I'm able to read the first matching value just fine when I pass, XPathConstants.STRING to the evaluate function.

alist = xpath.evaluate(exp, input, XPathConstants.NODESET); 
System.out.println(alist.item[0].getNodeValue());

Its throwing this error - javax.script.ScriptException: TypeError: Cannot read property "getNodeValue" from undefined in <eval>

Any ideas why the list would have all null valued elements?

1

There are 1 best solutions below

0
Luke Woodward On

The problem seems to be with the use of item[0] within the line

System.out.println(alist.item[0].getNodeValue());

alist appears to be a NodeList, and this interface contains two methods, getLength() and item(int index). If you want to get the first item in the list then you need to call the item method using item(0), rather than attempting to use item[0] to access item as if it were an array:

System.out.println(alist.item(0).getNodeValue());