Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable value from XML to JavaScript. Pure way

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?

like image 647
Kalinin Avatar asked Feb 28 '23 04:02

Kalinin


2 Answers

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
     });
   }
});
like image 177
buggy1985 Avatar answered Mar 08 '23 16:03

buggy1985


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);
}
like image 26
Anurag Avatar answered Mar 08 '23 15:03

Anurag