--- serialize.js ---
Array.prototype.toXml = function(t){
var s = new Array(), i, l = this.length, v;
var t2 = (t.charAt(t.length-1)=='s')?t.substring(0,t.length-1):t;
for(i=0;i<l;i++){
v = this[i];
switch (typeof v) {
case 'undefined':
case 'function':
case 'unknown':break;
case 'object':if(v!=null){s.push(v.toXml(t2));}break;
case 'string':v = v.toXml();
default:s.push('<'+t2+'>'+v+''+t2+'>');
}
}
if(s.length>1)return '<'+t+'>'+s.join('')+''+t+'>';
return s;
};
Object.prototype.toXml = function(t){
var sa = new Array(''), se = new Array('');
if(!t) t=this._tagName||'object';
for(var i in this){
if (this.hasOwnProperty(i) && i.charAt(0)!='_') {
var v = this[i];
switch (typeof v) {
case 'undefined':
case 'function':
case 'unknown':break;
case 'object':if(v!=null){se.push(v.toXml(i));}break;
case 'string':v = v.toXml();
default: sa.push(' '+i+'="'+v+'"');
}
}
}
var s = se.join('');
return '<'+t+sa.join('')+((s!='')?'>'+s+''+t+'>':'/>');
};
String.prototype.toXml = function(){
return this.replace('&','&').
replace('<','<').replace('>','>').
replace('\'',''').replace('"','"');
};
Sample Usage
<script language="javascript" src="serialize.js"></script>
<script language="javascript">
</script>
function Car(make,model,color){
this.make = make;
this.model = model;
this.color = color;
}
var cars = new Array();
cars.push(new Car('BMW','545i','Silver'));
cars.push(new Car('Toyota','Corrola','Red'));
cars.push(new Car('Honda','Accord','Black'));
//serialize to xml
alert(cars.toXml());
Note:
1. Private properties are prefixed with an underscore
2. You can add a default TagName for an object using the this._tagName property. For example in the Cars object above, you can add:
this._tagName = 'car';