Get variable value from XML to JavaScript. Pure way

17,486

Solution 1

How about jQuery?

$.ajax({
   type: "GET",
   url: "relative/path/to/yourfile.xml",
   dataType: "xml",
   success: function(xml) {
     $(xml).find('point').each(function(){
       var longitude = $(this).find('longitude').text()

       // doing something with your longitude variable
     });
   }
});

Solution 2

Use an XML parser assuming you have a string. If it's a file, AJAX should do the parsing heavy-lifting for you. Here's an example: http://jsfiddle.net/Jr5ga/

/**
 * Parse XML from string
 * Abstract away browser differences
 */
​function parseXML(text) {
    if (window.DOMParser) {
        parser = new DOMParser();
        doc = parser.parseFromString(text,"text/xml");
    }
    else { // Internet Explorer
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(text);
    }
    return doc;
}

To get the longitude values from this XML document, you can use the getElementsByTagName function. Once all longitude nodes are selected, loop through them and to get the text content in each node, call childNodes[0] since it only has 1 child - the text node, and call nodeValue on the text node to get the value as a string.

var xml = parseXML(string);

var longitudes = xml.getElementsByTagName("longitude");
var result = [];

for(var i = 0; i < longitudes.length; i++) {
    // add longitude value to "result" array
    result.push(longitudes[i].childNodes[0].nodeValue);
}

Solution 3

Making an AJAX call to the XML source can help you. But it depends on where you store the xml document.

Check out the following link, especially the XMLHttpRequest part:

http://www.w3schools.com/ajax/default.asp

Share:
17,486
Kalinin
Author by

Kalinin

Updated on June 14, 2022

Comments

  • Kalinin
    Kalinin almost 2 years

    I have XML:

    <point>
        ...
        <longitude>34.123123</longitude>
    </point>
    <point>
        ...
        <longitude>11.12534534</longitude>
    </point>
    <point>
        ...
        <longitude>32.567653</longitude>
    </point>
    <point>
        ...
        <longitude>33.345345</longitude>
    </point>
    ...
    

    Task:

    get values of <longitude> in javascript (in variable).

    Which is purest way?

    It is possible to do it without XSLT (without making dummy elements)?


    Update:

    I have very badly explained.

    XML it is dynamically formed on a server, then in the same place passes XSLT and it turns out HTML which is sent in a browser.

    Probably in HTML it is necessary to make a fictitious element in which to write down value of a longitude, then to read out its value in javascript from an element on page.

    How it is possible to make differently?