JScript XML Data Access

Published Tue, Apr 13 2004 23:10 | coad

“Random Vocabulary Word.js”

 

This simple JScript demonstrates just how easy it is to access data from an XML file through the Windows Scripting Host and MSHTML 4.0.  You must have “Vocabulary.xml” in the same directory when running.

 

 

// Created by Noah Coad, coad.net/noah, 4/13/04

 

xmlFile = "Vocabulary.xml";

 

var xml = new ActiveXObject("MSXML2.DOMDocument.4.0");

xml.validateOnParse = false;

xml.async = false;

xml.load(xmlFile);

 

if (xml.parseError.errorCode != 0)

   WScript.Echo("XML Parse Error : " + xml.parseError.reason);

else

{

   var root = xml.documentElement;

   var oNodeList = root.childNodes;

 

   // Select a random word

   var rnd = Math.floor(Math.random() * oNodeList.length);

  

   // Create a message

   var msg = oNodeList.item(rnd).selectSingleNode("Word").text;

   msg += "\n" + oNodeList.item(rnd).selectSingleNode("Desc").text;

 

   // Display the message

   WScript.Echo(msg);

}

 

 

 

Filed under: ,