June 26, 2009

Parsing XML in Sahi scripts

Sahi uses Rhino as its JavaScript engine and Rhino has excellent support for handling XML.

Below is a script which reads and asserts XML nodes and attributes. The example has been picked from http://www.ibm.com/developerworks/webservices/library/ws-ajax1/ so that it is easy to experiment with the IBM examples in this script

.var xmlStr = '' +
'' +
'   ' +
'      Ant' +
'      Shaggy' +
'      Blue' +'      176' +
'   ' +
'   ' +
'      Paul' +
'      Spiky' +
'      Grey' +
'      178' +
'   ' +
'';var $x = new XML(xmlStr);
_assertEqual("Ant", $x.person[0].name.toString());
_assertEqual("Grey", $x.person[1].eyes.toString());
for each (var $p in $x.person){
var $measure = $p.height.@measure.toString();
_assert($measure == "metric");
_assert($p.height > 170);

Two points to note:

1) All nodes that you access are of type xml. You will need to use toString() on them before you assert them.
2) Using @ from inside a Browser Action Function (like _click, _assert etc.) causes the script to fail because of a parsing error in Sahi's code. So first assign it to a variable and then use it, like it has been used for $measure. This bug will be fixed in the coming release.

There is a lot more that can be done with the XML object. Have a look at these links:

Continue reading