Javascript XML extensions

While several features of Microsoft's DOMDocument object are not supported by standards, it's hard to deny that many of them are quite useful, and probably should be standardized.

When writing AJAX web apps, you need easy access to XML nodes. And more than anything, you need it to be cross-browser capable. To that end, I often include the following script in my AJAX apps.

/**
 * XML functions
 */
if (window.ActiveXObject) {
	/* Functions for IE */
	domLoadXml=function(xml){
		var doc=new ActiveXObject('MSXML2.DOMDocument');
		doc.async=false;
		doc.loadXML(xml);
		return doc;
	}
}else{
	/* Functions for non-IE browsers */
	domLoadXml=function(xml){
		var parser=new DOMParser();
		return parser.parseFromString(xml,'text/xml');
	}
	//fill in the missing convenience methods for Firefox
	Element.prototype.selectSingleNode=function(xpath){
		var xpe=new XPathEvaluator();
		var n=xpe.evaluate(xpath,this,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);
		if(n!=null) return n.singleNodeValue;
		else return null;
	}
	Element.prototype.selectNodes=function(xpath){
		var xpe=new XPathEvaluator();
		var xpr=xpe.evaluate(xpath,this,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);
		var nodes=new Array();
		if(xpr!=null){
			var el=xpr.iterateNext();
			while(el){
				nodes.push(el);
				el=xpr.iterateNext();
			}
		}
		return nodes;
	}
	if(typeof HTMLElement.prototype.__defineGetter__ != 'undefined'){
		Element.prototype.__defineGetter__('xml', function() {return XMLSerializer().serializeToString(this);} );
		Element.prototype.__defineGetter__('text', function() {return this.textContent;} );
		Element.prototype.__defineSetter__('text', function(s) {this.textContent=s;} );
		//Element.prototype.__defineSetter__('xml', function(s) {} );
	}
}
comments powered by Disqus