0

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.

1
  • For some reason jQuery isnt loading the XML file. The chrome console reports xmlhttprequest cannot load [filename].xls Origin null is not allowed by access-control-allow-origin Commented Sep 7, 2012 at 2:27

2 Answers 2

1

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;
};
Sign up to request clarification or add additional context in comments.

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.