I am looking for a Javascript solution to this problem:
I have an XML document which is loaded by way of a typical AJAX method:
var xml = http.responseXML;
Consider the following example xml snippet:
<main>
<primary>
<enabled>true</enabled>
</primary>
<secondary>
<enabled>true</enabled>
</secondary>
</main>
I would like to get the value of a node by specifying the path as follows:
var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);
I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName
and the like.
How would I construct the method getNodeValueByPath
or is there some construct in Javascript that allows for this?
I am not well versed in Javascript.
EDIT: Here is an example that shows my attempt at using XPath and how it is failing:
XML:
<?xml version="1.0" ?>
<main xmlns="example.com">
<primary>
<enabled>true</enabled>
</primary>
<secondary>
<enabled>false</enabled>
</secondary>
</main>
JavaScript: (these are the relevant functions only)
function useHttpResponse()
{
if (http.readyState == 4)
{
if(http.status == 200)
{
var xml = http.responseXML;
var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
alert(evalue);
}
}
}
function getXMLValueByPath(nodepath, xml)
{
var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
return result;
}
I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.
Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com"
from the XML document, the alert dialog appears with the text "false" as desired.
Debugging using Firebug shows that resultNode
is an empty string as long as the namespace is declared.