Javascript - 解析自定义标签的最佳方式

时间:2013-08-20 00:47:11

标签: javascript ajax parsing

我写了一个返回以下内容的API

 <location><lat>41.47033705</lat><lon>-81.93612862</lon></location>
 <location><lat>41.470320224762</lat><lon>-81.9364535808563</lon></location>
 <location><lat>41.4704650640488</lat><lon>-81.9449239969254</lon></location>
 <location><lat>41.4780235290527</lat><lon>-81.8454140424728</lon></location>
 <location><lat>41.48597253</lat><lon>-81.82579113</lon></location>

我有一个AJAX调用,现在我需要在我的JavaScript中使用它。

最终我想和2d Array [lat,lon]

执行此操作的代码量最少?

4 个答案:

答案 0 :(得分:2)

假设响应是有效的XML,您可以使用getElementsByTagName并推送到数组:

var arr = [];
for (var location in response.getElementsByTagName('location'))
{
    arr.push([
        parseFloat(location.getElementsByTagName('lat')[0]), 
        parseFloat(location.getElementsByTagName('lon')[0])
    ]);
}

答案 1 :(得分:1)

只需使用JQuery的选择器引擎来解析代码。

将您的元素包裹在<div id="data"> ... </data>中以便于选择,您可以执行以下操作:

var _locations = $('#data').find('location');
var my_data = [];

$.each(_locations, function(index, loc) {
    var _lat = $(loc).find('lat');
    var _lon = $(loc).find('lon');

    my_data.push([_lat.text(), _lon.text()]);
})

// my_data will contain a 2D array of your lat, lon

好运

-Kiru

答案 2 :(得分:0)

您可以通过XmlHttmlRequest进行AJAX调用并获取responseXML。然后,您可以通过XmlDocument方法和属性解析数据。

您甚至可以对结果运行Xpath queries以准确选择所需内容。

答案 3 :(得分:0)

Regex 101 Demo

<强>正则表达式

<lat>([^<]+)<\/lat><lon>([^<]+)<\/lon>

使用g全球)标志

<强> 描述

<lat> Literal <lat>
1st Capturing group ([^<]+) 
    Negated char class [^<] 1 to infinite times [greedy] matches any character except:
        < The character <
<\/lat><lon> Literal </lat><lon>
2nd Capturing group ([^<]+) 
    Negated char class [^<] 1 to infinite times [greedy] matches any character except:
        < The character <
<\/lon> Literal </lon>

g modifier: global. All matches (don't return on first match)

<强> 可视化

Regular expression visualization


采取以上措施解决您的具体问题

DEMO jsFiddle

<强> JS

var text = " <location><lat>41.47033705</lat><lon>-81.93612862</lon></location><location><lat>41.470320224762</lat><lon>-81.9364535808563</lon></location><location><lat>41.4704650640488</lat><lon>-81.9449239969254</lon></location><location><lat>41.4780235290527</lat><lon>-81.8454140424728</lon></location><location><lat>41.48597253</lat><lon>-81.82579113</lon></location>";

var myregexp = /<lat>([^<]+)<\/lat><lon>([^<]+)<\/lon>/g;
var results = new Array();
var match = myregexp.exec(text);
while (match != null) {
    var result = new Array();
    for (var i = 1; i < match.length; i++) {
        result.push(match[i]);
    }
    results.push(result);
    match = myregexp.exec(text);
}

console.log(results);

变量results包含一个二维数组[lat,lon]