user1642579
user1642579

Reputation: 95

Loop through XML nodes and store as JavaScript variables

I am new to JavaScript and I am trying to read an XML file and extract its content into JavaScript variables.

Here is an example of the content of my XML file:

<!-- 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>

So, presuming that I have more data than this, can I create a loop or nested loops in JavaScript that reads the XML file and extracts the data into arrays? Examples of elements that I am interested in are: projectsites.title, projectsites.lat, developersites.title and developersites.lat.

Upvotes: 0

Views: 654

Answers (2)

gion_13
gion_13

Reputation: 41533

using jQuery to parse the xml, here's my implementation of a function that converts the xml to a 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;
};

Upvotes: 1

Russ
Russ

Reputation: 1951

You can use jQuery to easily get xml data and parse it. Here is an example:

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

Upvotes: 0

Related Questions