1

我有一个这样的 XML:

<?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 次。” 到目前为止,这是我尝试过的:

//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 ");
    }

}

我的新手试图看看我是否可以将 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] )
        }
    }

这让我很困惑。目前在输出面板中我得到...

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

有没有办法在跟踪输出中包含日期?所以我得到类似的东西:

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

1 回答 1

4

在解析 XML 之前,我不会从 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]);
}
于 2013-05-21T09:58:55.710 回答