views:

221

answers:

3

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?

+2  A: 

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

sahs
+1  A: 

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
     });
   }
});
buggy1985
+1  A: 

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);
}
Anurag
@Anurag, I so understand that the offered variant does not approach, because I have badly explained a problem. For realisation of your decision the line is necessary, and it at me is not present (it it is necessary to get from a server). Your reception very much was pleasant to me, I will remember it and I will apply in the future for XML parsing.
Kalinin