Introducing toXmlString : Javascript XML DOM to String Conversion
I was surprised to find no function to convert a javascript xml dom object to a string. I did find an upcoming feature added in Javascript 1.6 by the cool folks at Mozilla, but it really did not cater to xml dom objects already created /accessable by javascript.
I've seen PHP's PEAR ,and XML_Parser classes and often like to take part of the xml to resend/reuse later in my application. So since I could'nt find one , I wrote one 8 ) !
toXmlString(xmlObj) : string
/**
* @author Bhasker V Kode
* @name toXmlString
* @description Functional Style Method to Generate XML String from any xml DOMobject .
* @param s (String ) [optional for usage]
* @language Javascript
* @date 25th May ,2007
*/
- function toXmlString(xy,s){
-
var str = (s==undefined)?'' : s;
- if(xy.nodeValue==undefined){
- //ur a big moma
- var multiStr=[],temp='';
- for(var i=0;i
-
// each repeasted node
- if(xy.childNodes[i].nodeName.toString().indexOf('#')
- var nodeNameStart ='
- var nodeNameEnd ='';
- var attsStr=' ',atts = xy.childNodes[i].attributes;
-
if(atts!=undefined){
- for(var j=0;j
- attsStr+=atts[j].nodeName+'="'+ atts[j].firstChild.nodeValue+'"';
- }
- }
- temp = nodeNameStart + ((attsStr==' ')?'':attsStr ) +'>'+toXmlString(xy.childNodes[i],str) + nodeNameEnd;
- multiStr.push(temp);
- str = temp;
- }else{
-
//node Value
- str = toXmlString(xy.childNodes[i],str);
- multiStr.push(str);
- }
- }
-
//end of for loop,time to untangle our results in order of appearance
- str = multiStr.join('');
- }else{
- return xy.nodeValue;
- }
- return str;
-
}
Usage
var str = toXmlString(xmlDomObj) ;
Demo - http://bhaskervk.com/libraries/reusable/demos/xml.phpYou might find the functional style of programming familiar from my earlier posts ,where I created a XML writer class where I created an xml string from scratch . So it was only a matter of time before i approached the situation where I might need to create xml from existing objects.
Technorati Tags: kode, ,functional, ,, programming, ,, helper, ,class, ,, toXmlString, ,, bhasker,, xml