我正在使用以下网站查找海拔:
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(newinputStreamReader(connection.getinputStream()));StringBuilder sb = new StringBuilder();String line = null;line = rd.readline();while ((line = rd.readline()) != null){ sb.append(line + '\n');}
当我输出sb.toString()我得到Null
有任何想法吗?
解决方法:
我建议自己尝试解析XML,而不是尝试从Buffer中读取它,而无需自己亲自尝试.为此,您将需要了解XML树结构,因为您将基于Node进行阅读.例如:
// Data membersprivate URL URL;private inputStream stream;private documentBuilder builder;private document document;private Element root;private NodeList nodeList;URL = new URL(url); // The URL of the site you posted goes here.stream = URL.openStream();// Set up and initialize the document.documentBuilderFactory dbf = documentBuilderFactory.newInstance();dbf.setIgnoringElementContentWhitespace(true);builder = dbf.newdocumentBuilder();document = builder.parse(stream);document.getdocumentElement().normalize();root = document.getdocumentElement();nodeList = root.getChildNodes();// The number of calls to 'getFirstChild()' will vary with the complexity of// your XML tree. Also, 'i' Could vary as well, depending on which Node off// of the root you want to access.String number = nodeList.item(i).getFirstChild().getFirstChild().getNodeValue();
这似乎很令人困惑,但是让我给您一个XML示例.
<Building> <name>Train Station</name> <address>8 Main Street</address> <color>Blue</color></Building><Building> <name>Drugstore</name> <address>14 Howard Boulevard</address> <color>Yellow</color></Building>
每个建筑物代表一个不同的值,该值作为参数传递给“ .item(i)”.要访问有关第一个Building的信息,请传递一个值0.使用’.getFirstChild()’方法访问Building的子级,但是仅返回Node.如果需要文本“ Drugstore”,则必须遍历XML树到第二个项目的第一个孩子的数据. nodeList.item(1).getFirstChild().getNodeValue();
希望对您有所帮助!!
总结以上是内存溢出为你收集整理的Android简单XML解析全部内容,希望文章能够帮你解决Android简单XML解析所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)