XML sorting by attribute


/ Published in: ActionScript 3
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public static function sortXMLByAttribute
  2. (
  3. $xml : XML,
  4. $attribute : String,
  5. $options : Object = null,
  6. $copy : Boolean = false
  7. )
  8. :XML
  9. {
  10. //store in array to sort on
  11. var xmlArray:Array = new Array();
  12. var item:XML;
  13. for each(item in $xml.children())
  14. {
  15. var object:Object = {
  16. data : item,
  17. order : item.attribute($attribute)
  18. };
  19. xmlArray.push(object);
  20. }
  21.  
  22. //sort using the power of Array.sortOn()
  23. xmlArray.sortOn('order',$options);
  24.  
  25. //create a new XMLList with sorted XML
  26. var sortedXmlList:XMLList = new XMLList();
  27. var xmlObject:Object;
  28. for each(xmlObject in xmlArray )
  29. {
  30. sortedXmlList += xmlObject.data;
  31. }
  32.  
  33. if($copy)
  34. {
  35. //don't modify original
  36. return $xml.copy().setChildren(sortedXmlList);
  37. }
  38. else
  39. {
  40. //original modified
  41. return $xml.setChildren(sortedXmlList);
  42. }
  43. }
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50. var xml:XML =
  51. <body id="someId">
  52. <p displayOrder="15">Hello</p>
  53. <p displayOrder="7">World</p>
  54. <p displayOrder="3">Is</p>
  55. <p displayOrder="9">This</p>
  56. <p displayOrder="25">Thing</p>
  57. <p displayOrder="13">Working</p>
  58. </body>
  59.  
  60. // original XML object
  61. trace("BEFORE:" + xml);
  62.  
  63. XMLUtils.sortXMLByAttribute(
  64. xml,
  65. 'displayOrder'
  66. );
  67. trace("After:" + xml);
  68.  
  69. XMLUtils.sortXMLByAttribute(
  70. xml,
  71. 'displayOrder',
  72. Array.NUMERIC
  73. );
  74. trace("Array.NUMERIC:" + xml");
  75.  
  76. //multiple options not don't modify orginal
  77. var reverseXML:XML = XMLUtils.sortXMLByAttribute(
  78. xml,
  79. 'displayOrder',
  80. Array.NUMERIC | Array.DESCENDING,
  81. true
  82. );
  83. trace("Array.NUMERIC | Array.DESCENDING:" + reverseXML);

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.