How to Specify Namespace in XPath Expressions
To navigate to an element in an XML document, you can use selectNodes
or the selectSingleNode
method of DOM, thereby supplying an XPath expression to locate the node (or nodes) you want to select.
For example, to select the <greeting>
element in the following sample XML document:
<?xml version="1.0" encoding="utf-8" ?>
<myDoc>
<greeting>Hello World!</greeting>
<greeter>
<first-name>John</first-name>
<last-name>Doe</last-name>
</greeter>
</myDoc>
use the selectSingleNode
method as shown in the following JScript code fragment:
var d = new ActiveXObject("MSXML2.DOMDocument.5.0");
d.validateOnParse=false;
d.async = false;
d.load("mydoc.xml");
if (d.parseError.errorCode != 0 ) {
WScript.Echo("Error: " + d.parseError.reason + " \r\n");
}
else {
var node = d.selectSingleNode("/myDoc/greeting");
WScript.Echo(node.text);
When you run the previous JScript code, it prints the value of node.text
in a message box as output text:
Hello World!
However, if the same XML document is namespace qualified that is by updating the following line in the original XML files:
<?xml version="1.0" encoding="utf-8" ?> <myDoc xmlns:a="urn:myDoc"> <a:greeting>Hello World!</a:greeting> <greeter> <first-name>John</first-name> <last-name>Doe</last-name> </greeter> </myDoc>
you must then set the SelectionNamespaces
property on the DOM object prior to making your XPath selection. For example, update the previous JScript to insert the following line of code as the new first statement within the body of the else
statement:
d.setProperty("SelectionNamespaces", "xmlns:a='urn:myDoc'");
Next you need to adjust your XPath expression so that it uses QNames (fully namespace qualified names) instead of unqualified names in order to achieve the same results and output as "Hello World!" which uses the modified sample XML document.
For example, to retrieve the <a:greeting>
element, in the previous JScript code, you now need to have the XPath expression updated to read as follows:
var node = d.selectSingleNode("/myDoc/a:greeting");
If you fail to set the SelectionNamespaces
property with the appropriate namespace URI as shown above before calling selectSingleNode("/myDoc/a:greeting")
,
it will result in the following error:
Reference to undeclared namespace prefix: 'a'.