Entradas de Marzo 04UTC 2010 en Dave Ruiz blog

Os dejo una pequeña y sencilla función para realizar esta tarea en Javascript. Evidentemente, está sujeto a las mejoras que creáis convenientes.

function XMLString( object, name, recursiveCall ) {
	var xml = "", i;
	var isArray = typeof(object) === 'object' && typeof(object.length) === 'number' &&  !(object.propertyIsEnumerable('length')) && typeof(object.splice === 'function');
 
	if (!recursiveCall)	{
		xml += "<?xml version=\"1.0\" ?>";;
		xml += "<"+name+" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
	} else if (!isArray) {
		xml += "<"+name+">";
	}
 
	if (typeof(object) === "undefined" || object == null) return ""; //Nada
	else if (typeof(object) === "object") for (i in object) xml += XMLString( object[i], isArray?name:i, true); // Un objeto o array
	else xml += object; // Un texto
 
	if (!isArray || !recursiveCall) xml += "</"+name+">";
 
	return xml;
}

Y un ejemplo de uso sería:

var objeto = {
	campo1 : "valor1",
	campo2 : "valor2",
	campo3 : "valor3"
}
 
alert( XMLString( objeto, "XML" ) );

Donde el primer parámetro es el objeto a convertir, y el segundo es el nombre del elemento raíz. Con el ejemplo anterior obtendríamos como salida la siguiente cadena:

<?xml version="1.0" ?>
<XML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <campo1>valor1</campo1>
  <campo2>valor2</campo2>
  <campo3>valor3</campo3>
</XML>

Con 4 cambios es posible convertirlo en código AS2 o AS3. Aunque en estos casos creo que hay métodos mejores y nativos para hacer esta función.