The following JScript example shows how to use the SelectionNamespances property to specify namespaces in order to query elements that belong to different namespaces from an XML document.
XML File (example.xml)
The following example contains elements that belong to "a" and "b", in addition to elements that do not belong to any namespace.
<?xml version="1.0"?>
<root>
<branch>branch</branch>
<a:root xmlns:a="http://myserver.com">
<a:branch>a-branch</a:branch>
<b:branch xmlns:b="http://yourserver.com">
b-branch
</b:branch>
</a:root>
</root>
JScript Code
Notice that the following code uses "na" and "nb" as the namespace aliases for the "http://myserver.com" and "http://yourserver.com" namespaces. The corresponding namespace aliases are "a" and "b" in the input document (example.xml).
var dom = new ActiveXObject("MSXML2.DOMDocument.6.0");
dom.async= false;
dom.validateOnParse = false;
dom.load("example.xml");
if (dom.parseError.errorCode!=0)
{
alert("can't load dom" + dom.parseError.reason);
exit;
}
ns = "xmlns:na='http://myserver.com' xmlns:nb='http://yourserver.com'";
alert("ns:(before setProperty())\n "+dom.getProperty("SelectionNamespaces"));
dom.setProperty("SelectionNamespaces", ns);
alert("ns:(after setProperty())\n "+dom.getProperty("SelectionNamespaces"));
node = dom.selectSingleNode("//root");
alert("root: \n"+node.xml);
node = dom.selectSingleNode("//na:root");
alert("a:root: \n"+node.xml);
node = dom.selectSingleNode("//branch");
alert("branch: \n"+node.xml);
node = dom.selectSingleNode("//na:branch");
alert("a:branch: \n"+node.xml);
node = dom.selectSingleNode("//nb:branch");
alert("b:branch: \n"+node.xml);
function alert(str)
{
WScript.echo(str+"\n");
}
Try It!
-
Copy example.xml and example.js onto your local drive.
-
Open a command prompt and navigate to the directory where example.xml and example.js are located.
-
Type the following command from the command prompt:
You should get the following output.
ns:(before setProperty())
ns:(after setProperty())
xmlns:na='http://myserver.com' xmlns:nb='http://yourserver.com'
root:
<root>
<branch>branch</branch>
<a:root xmlns:a="http://myserver.com">
<a:branch>a-branch</a:branch>
<b:branch xmlns:b="http://yourserver.com">
b-branch
</b:branch>
</a:root>
</root>
a:root:
<a:root xmlns:a="http://myserver.com">
<a:branch>a-branch</a:branch>
<b:branch xmlns:b="http://yourserver.com">
b-branch
</b:branch>
</a:root>
branch:
<branch>branch</branch>
a:branch:
<a:branch xmlns:a="http://myserver.com">a-branch</a:branch>
b:branch:
<b:branch xmlns:b="http://yourserver.com">
b-branch
</b:branch>