其他分享
首页 > 其他分享> > Android简单XML解析

Android简单XML解析

作者:互联网

我正在使用以下网站查找海拔:

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

有任何想法吗?

解决方法:

我建议自己尝试解析XML,而不是尝试从Buffer中读取它,而无需自己亲自尝试.为此,您将需要了解XML树结构,因为您将基于Node进行阅读.例如:

// Data members
private 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();

希望对您有所帮助!!

标签:xml,android,xml-parsing
来源: https://codeday.me/bug/20191101/1986151.html