Tema: Ordenar XML
Ver Mensaje Individual
  #2 (permalink)  
Antiguo 19/02/2007, 17:32
Avatar de jahepi
jahepi
Colaborador
 
Fecha de Ingreso: diciembre-2004
Ubicación: Querétaro
Mensajes: 1.124
Antigüedad: 19 años, 4 meses
Puntos: 43
Re: Ordenar XML

Hola et43!

Hay una extensión que hizo Senocular de la clase XMLNode para ordenar los nodos en un xml, antes que nada copia este código, te paso la liga directa de las librerías de Senocular Librerís de Senocular pero el código sale mal en algunos puntos como el [], sale así <>, pero bueno aquí te pego el código correcto:

Código:
// Removes and returns an XML node based on index
XMLNode.prototype.extractChild = function(i){
	var n = this.childNodes[i].cloneNode(true);
	this.childNodes[i].removeNode();
	return n;
}

// Swap the positions of two child nodes within their parent's childNodes array
XMLNode.prototype.swapChildren = function(i, i2){
	if (i==i2) return(0);
	if (i > i2){
		var temp = i;
		i = i2; i2 = temp;
	}
	var n = this.extractChild(i);
	var n2 = this.extractChild(i2-1);
	this.insertBefore(n2, this.childNodes[i]);
	this.insertBefore(n, this.childNodes[i2]);
}

// Sort child nodes based on a compare function (uses a simple quicksort)
XMLNode.prototype.sortChildren = function(cmp, low,high) {
	var a = this.childNodes;
	if (cmp == undefined) cmp = this.sortChildren.defaultCompare;
	if (low == undefined) low = 0;
	if (high == undefined) high = a.length;
	var p = a[low], w = low+1, h = high;
	while(w < h) {
		if (cmp(a[w], p)) w++;
		else this.swapChildren(w, (--h));
	}
	this.swapChildren(low, (--w));
	if (w-low > 1) this.sortChildren(cmp, low, w);
	if (high-h > 1) this.sortChildren(cmp, h, high);
}
 
// A default sort function for use in sortChildren
XMLNode.prototype.sortChildren.defaultCompare = function(a,b){
	return a.nodeName <= b.nodeName;
}
Pega ese código en tu primer fotograma de la aplicación, ahorita viene lo interesante, para ordenar por títulos de acuerdo a tu xml, este es un ejemplo de como debes utilizarla:

Código:
var xml:XML = new XML();
xml.ignoreWhite = true;
xml.load("trabajos.xml");
xml.onLoad = function(success:Boolean):Void {
	if(success) {
	    this.firstChild.sortChildren(compareByTitle);
	    trace(this);
	}
};

function compareByTitle(a, b):Boolean {
	return a.childNodes[0].firstChild.nodeValue <= b.childNodes[0].firstChild.nodeValue;
}
Lo que me interesa comentarte es la función compareByTitle, si te fijas puse esto "a.childNodes[0].firstChild.nodeValue", eso equivale al valor que tienes en el nodo titulo, si tu quieres comparar el nodo "img" este equivale al nodo 1, entonces haría otra función de esta forma:

Código:
function compareByImage(a, b):Boolean {
	return a.childNodes[1].firstChild.nodeValue <= b.childNodes[1].firstChild.nodeValue;
}
Para aplicar esa comparación solo le pasas la referencia de la función como lo hice en el ejemplo anterior: "this.firstChild.sortChildren(compareByTitle)" .

Sale, cualquier pregunta aqui tamos XD

Saludos !