Android简单XML解析

时间:2012-01-24 15:34:20

标签: 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

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

你犯了一个小错误:

第一个rd.readLine()会返回您的<tag>number</tag>内容,但while循环会再次使用null删除它。删除第一个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("</"));

答案 1 :(得分:1)

如果没有亲自尝试,我建议尝试解析 XML,而不是试图从缓冲区中读取它。要非常详细地执行此操作,您需要了解XML树结构,因为您将基于Nodes读取。例如:

// 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。如果你想要文本“药店”,你必须遍历XML树到第二项的第一个孩子的数据,例如。 nodeList.item(1).getFirstChild().getNodeValue();

我希望有所帮助!!