2013-05-21 83 views
0

我有一個XML這是這樣的:解析XML使用ActionScript 3.0

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Row> 
     <ColumnA>2013-08-07</ColumnA> 
     <ColumnB>Pizza</ColumnB> 
    </Row> 
    <Row> 
     <ColumnA>2013-04-07</ColumnA> 
     <ColumnB>Burger</ColumnB> 
    </Row> 
    <Row> 
     <ColumnA>2013-04-07</ColumnA> 
     <ColumnB>Pizza</ColumnB> 
    </Row> 

的XML這樣下去了數百行。我試圖達到的是這個。 「輸出:比薩:2013-08-07 & 2013-04-07發生2次。」到目前爲止,這是我已經試過:在想看看我能與列B到A列

var columnB:String; 

    for (var i:uint=0; i<rows.length(); i++) 
    { 
     if (columnA[i] == myXML.Row.ColumnA[i]) 
     { 
      trace(columnA[i], "=", columnB[i]) 
     } 
    } 

它是我百思不得其解

//Variables 
var myXML:XML; 
var xmlLoader:URLLoader = new URLLoader(); 

//Check that the XML is loaded 
xmlLoader.load(new URLRequest ("myXML.xml")); 
xmlLoader.addEventListener(Event.COMPLETE, processXML); 
function processXML(e:Event):void { 
    myXML = new XML(e.target.data); 

    //Create a XMLList for Column A data 

    var items:XMLList = myXML.Row.ColumnA.text() 

    //Create a XMLList for Rows 

    var rows:XMLList = myXML.Row 

    //Create a XMLList for Column B data (Dates) 
    var dates:XMLList = myXML.Row.ColumnB.text() 

    //Create an empty object to fill in the occurances of Column A 
    var columnA:String; 
    var map:Object = {}; 
    for each (columnA in items) 
    { 
     if(!map[columnA]) 
      map[columnA] = 1; 
     else 
      map[columnA]++; 
    } 


    for (columnA in map) 
    { 
     trace(columnA, "=", map[columnA], "times. On dates "); 
    } 

} 

我的新手嘗試。目前在輸出面板我得到...

Pizza 2 times. On Dates 
Burger 1 times. On Dates 
etc. 

有沒有辦法在跟蹤輸出中包含日期?所以我得到的是這樣的:

Pizza 2 times. On Dates 2013-08-07, 2013-04-07 

回答

3

從XML解析它之前,我不會提取任何東西:

var map:Object = {}; 
var meal:String;  
//loop through each row 
for each (var node:XML in myXML.Row) 
{ 
    meal = node.ColumnB.text(); 

    //if the meal does not exist as a key in our map yet, create it and put an empty array in it 
    if (!map[meal]) 
    map[meal] = []; 

    //fill the array of dates with the current date 
    map[meal].push(node.ColumnA.text()); 
} 

有你得到一個物體填滿這樣的:

{Pizza: ["2013-08-07", "2013-04-07"], Burger: ["2013-04-07"]} 

你只需要經過它:

for (var meal:String in map) 
{ 
    trace(meal, "found", map[meal].length, "times on", map[meal]); 
} 
+0

Thankyou K odiak!我是一名初學者,如果您可以添加解釋每行代碼的註釋,我會非常高興。 – rohan

+0

它跟蹤「比薩發現1次在2013-08-07 比薩發現1次在2013-04-07 漢堡在2013-04-07發現1次」 我怎樣才能使它計數在所有日期的總髮生次數。例如:「比薩:2發生日期:2013-08-07,2013-04-07」 – rohan

+0

我完全複製了上面的代碼,2013年在2013-04-07 上發現了1次Burger發現了1次比薩2013年發現了2次比薩-08-07,2013-04-07' – Kodiak