XML Parser in Javascript copyright 2006 by Fred Janon. Contact me for any use of this code at [email protected].

The parser supports attributes but not CDATA. It was tested with Netscape 8.1, Firefox 1.5, IE6 & Opera 7.51. It has a small footprint (about 3kbytes) and should run on browsers in embedded devices like PDAs and phones if they support Javascript 1.2. The parser can be easily made Javascript 1.1 compatible if needs be and the footprint reduced quite a bit if attribute support is not needed. The parsing is done entirely in the browser. It still has to be tested on Openwave Browser, Palm and RIM. The parser transforms the XML stream into DataObjects structures. A DataObject has 3 members: name (comes from the XML element/tag name), value (comes from the element data if any or null) and children, an array of DataObjects that contains the elements contained in the element as well as the attributes). See the DataObject definition below.



Usage: type or paste your XML string in the input text area and click on "Parse it!". The result will show in the Data Output box.

Time to parse: 0 milliseconds for 0 characters

Data Output


// DataObject used by XMLParser.js to represent the XML data
// - name = element name
// - value = element data (if any, null by default)
// - children = array of DataObject if there are embedded elements in this element
// - depth is used for display and debug

function DataObject(newName, newValue)
	{
	 this.name = newName;
	 this.value = newValue || null;
	 this.children = null;
	 this.depth = 0;
	}

DataObject.prototype.toString = function()
{
	var numChildren = 0;
	var i = 0;
	var ident = "";
	if (this.children) numChildren = this.children.length;
	var zStr = this.name + " = " + this.value;
	if (this.value == null) zStr = this.name + " = null";
		else zStr = this.name + " = '" + this.value + "'";
	if (numChildren != 0)
		{
		 for (i = 0 ; i <= this.depth ; i++) ident += this.identStr;
		 for (i in this.children) zStr += this.newlineStr + ident + this.children[i];
		}
	return zStr;
}

Hosted by www.Geocities.ws

1