Android简单XML解析

标签 android xml xml-parsing

我正在使用以下网站查找高程:

http://gisdata.usgs.gov/xmlwebservices2/elevation_service.asmx/getElevation?X_Value=-78.85834070853889&Y_Value=43.869369104504585&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=true

这会以 XML 格式提供格式为 93.7665481567383 的结果。

有人知道为我的 android 程序提取此数据的快速简单方法吗?

我尝试了以下操作,但输出一直为“null”。

HttpURLConnection connection = null;
URL serverAddress = null;
serverAddress = new URL("http://gisdata.usgs.gov/xmlwebservices2/elevation_service.asmx/getElevation?X_Value=-78.85834070853889&Y_Value=43.869369104504585&Elevation_Units=METERS&Source_Layer=-1&Elevation_Only=true");

connection = null;
connection = (HttpURLConnection)serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(10000);

connection.connect();
BufferedReader rd  = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();

String line = null;
line = rd.readLine();
while ((line = rd.readLine()) != null)
{
    sb.append(line + '\n');
}

当我输出 sb.toString() 时我得到 Null

有什么想法吗?

最佳答案

你犯了一个小错误:

第一个rd.readLine()返回您的 <tag>number</tag>东西但whilenull 循环删除它再次。删除第一个 rd.readLine()调用它应该工作。

String line = null;
line = rd.readLine(); // you get the only line... remove it!
while ((line = rd.readLine()) != null) {
    sb.append(line + '\n');
}

要获取您的电话号码,请尝试使用如下方式:

// line should contain your string...
line = line.substring(line.indexOf(">"), line.indexOf("</"));

关于Android简单XML解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8989507/

相关文章:

javascript android window.onorientationchange 连续触发

android - 找不到 ksoap2 HttpTransport 类

java - 如何将 Java 2D Shape 对象序列化为 XML?

xml - IDML 中故事 XML 的逻辑顺序

C++ 和 XML 绑定(bind)简单类型

Jquery 对象innerHTML 在 Firefox 中工作但在 IE 中不起作用?

android - 导出文件夹内的数据

android - ICS 中的 SimpleCursorAdapter

php - 如何使用 PHP 的 simplexml 遍历 XML 子节点

xml - 无法在 XSL-FO 中设置初始页码