2010-01-10 17 views
0

所以我有一個稍微棘手的問題......AS3:插入XML元素的字母順序對A樓盤

我產生一類我寫中的XML文件。比方說,這是開始XML:

<base> 
    <container id="0"> 
     <element type="Image" x="0" y"0" /> 
     <element type="Image" x="100" y"0" /> 
    <container/> 
</base> 

我要添加其他<element>的。排序的第一個順序是「type」,然後是「x」,然後是「y」。因此,如果我添加一個新的「類型」<element>,讓我們說輸入「文本」,我想在任何「圖像」<element>之後插入文本。

例如:

<base> 
    <container id="0"> 
     <element type="Image" x="0" y"0" /> 
     <element type="Image" x="100" y"0" /> 
     <element type="Text" x="200" y"100" /> 
    <container/> 
</base> 

的基本思想是保持排序列表,添加更多<element>的每個<container> ...數值排序是很簡單的,但我想不出一個乾淨的方式來按字母順序排序。

建議表示讚賞。

我能想到的唯一方法就是將類型轉換爲數組。添加「新類型」,排序並調用indexOf()...該數字應該是我應該插入的當前位置?感覺到kludgy。

回答

0

我建議將所有現有的XML元素讀入數組,添加新元素,對數組進行排序,然後寫出每個元素。這可能比試圖找出每個新元素應插入哪個索引更容易。這可能不是非常有效,但取決於你的情況。

對於做排序,我會嘗試像這樣(未經):

array.sort(function (a:XML, b:XML) { 
    if ([email protected] < [email protected]) return -1; 
    if ([email protected] > [email protected]) return +1; 
    if (Number([email protected]) != Number([email protected])) return Number([email protected]) - Number([email protected]); 
    return Number([email protected]) - Number([email protected]); 
}); 

編輯:添加投下的比較排序功能。

0

你能改變XML結構嗎?您可以將所有圖像元素包裹在<images>節點中,將文本元素包裹在<texts>節點中等等,這樣將元素添加到正確的位置將很容易。

您仍然可以通過訪問base.container.*.element獲取所有<element>節點。

-1

已測試......假設您擁有有效的XML,並且您爲具有與原始XML相同的根子項的已排序XML創建變量。我的恰巧是設備。

var sortedXML:XML = <devices></devices>; 

function sortBy(xmlFile:XML , field:String, order:int) 
{ 
    // array that will hold index of nodes 
    var arr:Array = new Array(); 
    // loop through nodes 
    for each (var someNode:XML in xmlFile.*) 
    { 
     // array gets populated with node that matches 'field' 
     arr.push(someNode.child(field)); 
    } 
    // sort the 'arr' array alphabetically 
    arr.sort(); 

    // reverse the alphabetical order if necessary 
    if (order == -1) 
    { 
     arr.reverse(); 
    } 

    // append the nodes in from the source, in the order of the array 
    for (var i:int=0; i<arr.length; i++) 
    { 
    sortedXML.appendChild(myXML.device.(child(field) == arr[i])); 
    } 
} 
// trace your original xml then trace sortedXML to verify 
+0

確保你注意到沒有,有在本例中的函數沒有呼叫......我的XML的電話是由ID節點 sortBy到我的設備進行排序(myXML,「設備ID」,1);除-1以外的任何整數都將按字母順序升序排列...可能應該將if(order == -1)更改爲if(order <0),然後正數排序前向,並且排除反向排序。 – Breezy3Stacks 2014-01-10 15:21:18

相關問題