Showing posts with label XPath. Show all posts
Showing posts with label XPath. Show all posts

Thursday, March 6, 2008

Javascript and XPath

In IE once an xml file has been loaded we need to set a property so that XPath can be used:

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("someFile.xml");
xmlDoc.setProperty("SelectionLanguage","XPath");

for other browsers like Firefox we need to set :

xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load("someFile.xml");
var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);

before calling the evaluate() method.

'selectionsPath' is the xpath expression that we need to form and then for getting the value(s),

//Internet explorer
if (ie)
{
var actions = xmlDoc.selectNodes(selectionsPath);
var i = 0;
for (i=0;i<actions.length;i++)
{
alert(actions[i].childNodes[0].nodeValue);
}
}
else
{
//mozilla
var actions = xmlDoc.evaluate(selectionsPath, xmlDoc, nsResolver, XPathResult.ANY_TYPE,null);
var result=actions.iterateNext();

while (result)
{
alert(result.textContent);
result=actions.iterateNext();
}
}