Jan 29, 2012

Reading a XML configuration file in JavaScript

This is just a simple code sample to read settings kept in XML configuration file, while you are working in client side. Below is the sample of my configuration file. It contains key/value pairs of settings.

<?xml version="1.0"?>
<Configuration xmlns="http://www.abc.com.au">
  <Appsetting Name="httpServer">abc:5555</Appsetting>
  <Appsetting Name="OrgName">abcLtd</Appsetting>
  <Appsetting Name="PriceAccessCode">NUOD66701</Appsetting>
</Configuration>

This is the JavaScript method which could be used to access those.

readConfigFileSettings = function (_url, _reqTag)
{
var objXML = new ActiveXObject("Microsoft.XMLDOM");
objXML.async = false;
objXML.load(_url);
if (objXML.parseError.errorCode != 0)
{
    alert("Error reading file : " + objXML.parseError.reason);
    return null;
}

var config = objXML.selectSingleNode("//Configuration");
var _retrunStr = '';
for (var i = 0; i < config.childNodes.length; i++)
{
 if (config.childNodes[i].attributes[0].nodeTypedValue == _reqTag)
 {
 _retrunStr = config.childNodes[i].nodeTypedValue;
 }
}
if (_retrunStr == '')
{
    _retrunStr = reqTag + ' cannot be found in config file';
}
return _retrunStr;
}

_Url parameter is to give the path of the configuration file (example 'C:\\inetpub\\wwwroot\\AbcAndCompany\\abcAdmin.config';) and _reqTag is the required tag (example: httpServer, OrgName or PriceAccessCode)

No comments:

Post a Comment