Get the value of a variable from XML in JavaScript. Clean 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 <longitude>in javascript (in a variable).

What is the cleanest way?

Can this be done without XSLT (without creating dummy elements)?


Update:

I explained very poorly.

XML is dynamically generated on the server, then XSLT passes in the same place and HTML is received, which is sent in the browser.

Probably, in HTML you need to make a dummy element in which you need to write the longitude value, and then read its value in javascript from the element on the page.

How can I do it differently?

+3
source share
3 answers

What 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
     });
   }
});
+4

AJAX XML . , XML-.

, XMLHttpRequest:

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

+2

XML-, . , AJAX . : 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;
}

XML, getElementsByTagName. , node, childNodes[0], 1 - node nodeValue node .

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);
}
+2

Source: https://habr.com/ru/post/1741947/


All Articles