我如何解析xml以在android模拟器中显示内容?
问题描述:
我在我自己的主机上有一个外部mysql数据库,我也在服务器端创建了php文件,它将从数据库中提取记录并将它们置于xml格式。 (如下所示)我如何解析xml以在android模拟器中显示内容?
<?php
mysql_connect("localhost","username","password") or die("Could not connect to host.");
mysql_select_db("footieDB") or die("Could not find database.");
$resultID=mysql_query("select * from league"); //$resultID was $sql
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<leagues>\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "\t<league>\n";
$xml_output .= "\t\t<leagueID>" . $row['leagueID'] . "</leagueID>\n";
$xml_output .= "\t\t<leagueName>" . $row['leagueName'] . "</leagueName>\n";
$xml_output .= "\t</league>\n";
}
$xml_output .= "</leagues>";
echo $xml_output;
mysql_close();
?>
我在想如何解析这个xml以便在android模拟器中显示信息。 任何例子将不胜感激。
在此先感谢。
答
说实话,你应该把数据放在JSON格式而不是XML中。 XML解析并不好玩,JSON也很快捷。如果你决定虽:
String example1;
String example2;
// establish a connection with the server
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www........./your_stuff.xml");
// execute the post and get the response
HttpResponse response = httpclient.execute(httpget);
byte[] responsebody = EntityUtils.toByteArray(response.getEntity());
String result = new String(responsebody, 0, responsebody.length, "UTF-8");
// Go through the XML with an XML pull parser, identifying items
// by their tag names
final XmlPullParser xpp = Xml.newPullParser();
xpp.setInput(new StringReader(result));
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("example1")) {
eventType = xpp.next();
example1 = xpp.getText();
} else if (xpp.getName().equalsIgnoreCase("example2")) {
eventType = xpp.next();
example2 = xpp.getText();
}
}
eventType = xpp.next();
}
....... etc
http://www.google.com.ng/search?sourceid=chrome&ie=UTF-8&q=parse+xml+android – Mob 2012-02-21 20:51:34