Share via


JScript Code (importNode.js)

 

[This sample code uses features that were implemented only in MSXML 6.0.]

main();

function main() 
{
  try {
    domFree = new ActiveXObject("MSXML2.FreeThreadedDOMDocument.6.0");
    domApt = new ActiveXObject("MSXML2.DOMDocument.6.0");
  }
  catch (e) {
    WScript.Echo("Microsoft XML Core Services (MSXML) 6.0 is not installed.\n"
          +"Download and install MSXML 6.0 from https://msdn.microsoft.com/xml\n"
          +"before continuing.");
    return;
  }

  domApt.async = false;
  domApt.load("doc1.xml");

  domFree.async = false;
  domFree.load("doc2.xml");

  // Copy a node from domFree to domApt:
  //   Fetch the "/doc" (node) from domFree (doc2.xml).
  //   Clone node for import to domApt.
  //   Append  clone to domApt (doc1.xml).
  // 
  var node = domFree.selectSingleNode("/doc");
  var clone = domApt.importNode(node, true);
  domApt.documentElement.appendChild(clone);
  domApt.documentElement.appendChild(domApt.createTextNode("\n"));
  WScript.Echo("doc1.xml after importing /doc from doc2.xml:\n"+domApt.xml);

  // Clone a node using importNode() and append it to the same DOM:
  //   Fetch the "doc/b" (node) from domApt (doc1.xml).
  //   Clone node using importNode on domApt.
  //   Append clone to domApt (doc1.xml).
  //
  var node = domApt.selectSingleNode("doc/b");
  var clone = domApt.importNode(node, true);  
  domApt.documentElement.appendChild(domApt.createTextNode("\t"));
  domApt.documentElement.appendChild(clone);
  WScript.Echo("doc1 after importing /doc/b from self:\n"+domApt.xml);

  // Clone a node and append it to the dom using cloneNode():
  //   Fetch "doc/a" (node) from domApt (doc1.xml).
  //   Clone node using cloneNode on domApt.
  //   Append clone to domApt (doc1.xml).
  //
  var node = domApt.selectSingleNode("doc/a");
  var clone = node.cloneNode(true);
  domApt.documentElement.appendChild(clone);
  WScript.Echo("doc1 after cloning a /doc/a from self:\n" + domApt.xml);

  domApt.save('out.xml');
  WScript.Echo("a new document was saved to out.xml in the current working directory.");
}

Try It!

  1. Copy the first piece of XML data (doc1.xml), and paste it into a text file. Save the file as doc1.xml.

  2. Copy the second piece of XML data (doc2.xml), and paste it into a text file. Save the file as doc2.xml, in the same directory where you saved doc1.xml.

  3. Copy the JScript listing above, and paste it into a text file. Save the file as importNode.js, in the same directory where you saved doc1.xml and doc2.xml.

  4. Double click the importNode.js file from Windows Explorer to launch the application. Alternatively, you can type "importNode.js" from a command prompt.

    Note

    Under operating systems other than Windows 2000 or Windows XP, you might need to install Windows Scripting Host (wscript.exe), if it is not already installed.

  5. Verify that your output is the same as that listed in Output for the importNode Example.