Compartilhar via


Source: queryNodes.js

 

This example application calls both the selectSingleNode method and the selectNodes method on an XML DOM object loaded from the stocks.xml file. The same XPath expression is input to both methods:

//stock[0]/*  

This expression specifies all the child elements of the first <stock> element in the XML document. In MSXML, the selectSingleNode method returns the first element of the resultant node-set, and the selectNodes method returns all the elements in the node-set.

Programmatically, this source code performs the following steps:

  1. Creates an instance of an XML DOM object (oXMLDom).

  2. Calls the load method on oXMLDom to load XML data from a file (stocks.xml).

  3. Calls the selectSingleNode method on oXMLDom to select a DOM node according to the input XPath expression (//stock[0]/*). Then displays the resulting node in the console if the query is successful.

  4. Calls the selectNodes method on oXMLDom to select a DOM node-set according to the input XPath expression ("//stock[0]/*"). Then displays the resulting nodes in the console if the query is successful.

JScript Source File (queryNodes.js)

main();

function main()
{
  var dom = LoadDOM("stocks.xml");
  try 
  {
    // Query a single node.
    var oNode = dom.selectSingleNode("//stock[1]/*");
    if (oNode != null)
    {
       alert("Result from selectSingleNode:\n" +
             "Node, <"+oNode.nodeName + ">:\n\t" +
              oNode.xml + "\n\n");
       oNode = null;
    } 

    // Query a node-set.
    alert("Results from selectNodes:\n");
    var oNodes = dom.selectNodes("//stock[1]/*");

    for (i=0; i<oNodes.length; i++)
    {
       oNode = oNodes.nextNode;
       if (oNode != null) 
       {
          alert("Node ("+i+"), <"+ oNode.nodeName + ">:\n\t" +
                oNode.xml);
       }
    }
  }

  catch (e)
  {
    alert(e.description);
  }
}


function LoadDOM(file)
{
   var dom;
   try {
     dom = MakeDOM(null);
     dom.load(file);
   }
   catch (e) {
     alert(e.description);
   }
   return dom;
}

function MakeDOM(progID)
{
  if (progID == null) {
    progID = "msxml2.DOMDocument.6.0";
  }

  var dom;

  try {
    dom = new ActiveXObject(progID);
  dom.setProperty("ResolveExternals", true);  
    dom.async = false;
    dom.validateOnParse = false;
    dom.resolveExternals = true;
  }
  catch (e) {
    alert(e.description);
  }
  return dom;
}

function alert(str)
{
  WScript.Echo(str);
}

To add queryNodes.js to the project

  1. Copy the code listing above. Paste it into the JScript code editor, and save the file as queryNodes.js in the current project folder.

Next, we'll add the resource files to the queryNodes project.