用于在Javascript中将我的XML文件的内容加载到数组中的脚本

时间:2009-11-26 15:39:14

标签: javascript xml

我有一个XML文件,可以查看here,有关一系列音乐专辑的数据,我想将这些数据加载到javascript中,形成一个名为“mymusic”的数组:

mymusic = [
  {
    title:,
    artist:,
    artwork:,
    tracks: [
      {
        tracktitle:,
        trackmp3:
      },
      {
        tracktitle:,
        trackmp3:
      }
    ]
  }
];

等;所以基本上是一个专辑阵列,每个专辑由一个记录代表,其中的字段是专辑标题,专辑艺术家,专辑插图和专辑曲目的数组(其中每个曲目/索引的数组由包含字段tracktitle和trackmp3的记录。

为了实现这一点,我有以下javascript:

function getxml(){
    xmldoc = XML.load('music.xml');

    var xmlalbums = xmldoc.getElementsByTagName('album');
    mymusic = [];
    for(i = 0; i < xmlalbums.length; i++){
        xmlalbum = xmlalbums[i];
        mymusic[i] = {};
        mymusic[i].title = dataFromTag(xmlalbum,'title');
        mymusic[i].artist = dataFromTag(xmlalbum,'artist');
        mymusic[i].artwork = dataFromTag(xmlalbum, 'artwork');
        tracks = [];

        var xmltracks = xmlalbums[i].getElementsByTagName('track');
        for(var a = 0; a < xmltracks.length; a++){
            xmltrack = xmltracks[i];
            tracks[i] = {};
            tracks[i].tracktitle = dataFromTag(xmltrack, 'title');
            tracks[i].trackmp3 = dataFromTag(xmltrack, 'mp3');
            mymusic[i].tracks = tracks;
        }
    }
}

然而,这并没有按照我想要的方式加载music.xml的内容,但我不明白为什么会这样。任何建议或帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

应该有效

function getxml(){
    xmldoc = XML.load('music.xml');

    var xmlalbums = xmldoc.getElementsByTagName('album');
    mymusic = [];
    for(i = 0; i < xmlalbums.length; i++){
        xmlalbum = xmlalbums[i];
        mymusic[i] = {};
        mymusic[i].title = dataFromTag(xmlalbum,'title');
        mymusic[i].artist = dataFromTag(xmlalbum,'artist');
        mymusic[i].artwork = dataFromTag(xmlalbum, 'artwork');

        tracks = [];
        var xmltracks = xmlalbums[i].getElementsByTagName('track');
        for(var a = 0; a < xmltracks.length; a++){
            xmltrack = xmltracks[a];
            tracks[a] = {};
            tracks[a].tracktitle = dataFromTag(xmltrack, 'title');
            tracks[a].trackmp3 = dataFromTag(xmltrack, 'mp3');
        }

        mymusic[i].tracks = tracks;
    }
}