Return to Snippet

Revision: 42258
at March 2, 2011 09:20 by mediapoint


Initial Code
public static function sortXMLByAttribute
 	(
		$xml		:	XML,
		$attribute	:	String,
		$options	:	Object	=	null,
		$copy		:	Boolean	=	false
	)
	:XML
 {
	//store in array to sort on
	var xmlArray:Array	= new Array();
	var item:XML;
	for each(item in $xml.children())
	{
		var object:Object = {
			data	: item, 
			order	: item.attribute($attribute)
		};
		xmlArray.push(object);
	}

	//sort using the power of Array.sortOn()
	xmlArray.sortOn('order',$options);

	//create a new XMLList with sorted XML
	var sortedXmlList:XMLList = new XMLList();
	var xmlObject:Object;
	for each(xmlObject in xmlArray )
	{
		sortedXmlList += xmlObject.data;
	}
	
	if($copy)
	{
		//don't modify original
		return	$xml.copy().setChildren(sortedXmlList);
	}
	else
	{
		//original modified
		return $xml.setChildren(sortedXmlList);
	}
 }






var xml:XML =
<body id="someId">
        <p displayOrder="15">Hello</p>
        <p displayOrder="7">World</p>
        <p displayOrder="3">Is</p>
        <p displayOrder="9">This</p>
        <p displayOrder="25">Thing</p>
        <p displayOrder="13">Working</p>
</body>

// original XML object
trace("BEFORE:" + xml);

XMLUtils.sortXMLByAttribute(
	xml,
	'displayOrder'
);
trace("After:" + xml);

XMLUtils.sortXMLByAttribute(
	xml,
	'displayOrder', 
	Array.NUMERIC
);
trace("Array.NUMERIC:" + xml");

//multiple options not don't modify orginal
var reverseXML:XML = XMLUtils.sortXMLByAttribute(
	xml,
	'displayOrder', 
	Array.NUMERIC | Array.DESCENDING, 
	true
);
trace("Array.NUMERIC | Array.DESCENDING:" + reverseXML);

Initial URL
http://www.mediapoint.gr/

Initial Description

                                

Initial Title
XML sorting by attribute

Initial Tags
sort, xml

Initial Language
ActionScript 3