Friday, May 25, 2007

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
*/


  1. function toXmlString(xy,s){
  2. var str = (s==undefined)?'' : s;
  3. if(xy.nodeValue==undefined){
  4. //ur a big moma
  5. var multiStr=[],temp='';
  6. for(var i=0;i <>
  7. // each repeasted node
  8. if(xy.childNodes[i].nodeName.toString().indexOf('#')<0){
  9. var nodeNameStart ='<'+xy.childNodes[i].nodeName;
  10. var nodeNameEnd ='';
  11. var attsStr=' ',atts = xy.childNodes[i].attributes;
  12. if(atts!=undefined){
  13. for(var j=0;j<>
  14. attsStr+=atts[j].nodeName+'="'+ atts[j].firstChild.nodeValue+'"';
  15. }
  16. }
  17. temp = nodeNameStart + ((attsStr==' ')?'':attsStr ) +'>'+toXmlString(xy.childNodes[i],str) + nodeNameEnd;
  18. multiStr.push(temp);
  19. str = temp;
  20. }else{
  21. //node Value
  22. str = toXmlString(xy.childNodes[i],str);
  23. multiStr.push(str);
  24. }
  25. }
  26. //end of for loop,time to untangle our results in order of appearance
  27. str = multiStr.join('');
  28. }else{
  29. return xy.nodeValue;
  30. }
  31. return str;
  32. }



Usage

var str = toXmlString(xmlDomObj) ;

Demo - http://bhaskervk.com/libraries/reusable/demos/xml.php



You 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: , , , , , , , , , , ,