循环遍历XML节点并存储为JavaScript变量

时间:2012-09-06 06:16:42

标签: javascript xml

我是JavaScript的新手,我正在尝试读取XML文件并将其内容提取到JavaScript变量中。

以下是我的XML文件内容的示例:

<!-- Locations of current projects -->
<projectsites>
 <li>
  <title>Battling Ninja Army</title>
  <location>Osaka, Japan</location>
  <lat>34.69</lat>
  <lon>135.50</lon>
 </li>
 <li>
  <title>Software Development</title>
  <location>Vienna, Austria</location>
  <lat>48.21</lat>
  <lon>16.37</lon>
 </li>
</projectsites>
<!-- Locations of current developers -->
<developersites>
 <li>
  <title>Brisbane office</title>
  <location>Brisbane, Australia</location>
  <lat>-27.4</lat>
  <lon>153</lon>
 </li>
 <li>
  <title>Phillipines Office</title>
  <location>Manilla, Phillipines</location>
  <lat>14.7</lat>
  <lon>121</lon>
 </li>
</developersites>

因此,假设我有比这更多的数据,我可以在JavaScript中创建一个循环或嵌套循环来读取XML文件并将数据提取到数组中吗?我感兴趣的元素示例有:projectsites.titleprojectsites.latdevelopersites.titledevelopersites.lat

2 个答案:

答案 0 :(得分:1)

使用jQuery解析xml,这是我将xml转换为json的函数的实现:

function xmlToObject(xml) {
    if (xml instanceof jQuery) xml = xml.get(0);
    var o = {};

    function level(node, obj) {
        obj[node.nodeName] = {};
        $.each(node.attributes, function (i, attr) {
            obj[node.nodeName][attr.name] = attr.value;
        });
        $(node).children().each(function (i, child) {
            level(child, obj[node.nodeName]);
        });
    }
    if (xml.nodeName === '#document' || xml.nodeName === 'document') 
        $(xml).children().each(function (i, child) {
            level(child, o);
        });
    else 
        level(xml, o);

    return o;
};

答案 1 :(得分:0)

您可以使用jQuery轻松获取xml数据并解析它。这是一个例子:

var projectsite_titles = [];
$.get('myXmlFile.xml', function(responseXml) {
   $(responseXml).find('projectsites li title').each(function () {
      projectsite_titles.push($(this).text());
   });
}, 'xml');