是否通过http教程或示例读取了有效的xml?
我有一个服务器,其中包含下一行url:http://192.168.0.1/update.xml
:
<?xml version='1.0' encoding='UTF-8'?>
<Version>1</Version>
我想向TextView显示“1”数字。我该怎么办?
答案 0 :(得分:2)
这是一段你可以适应你的愿望的代码:
获取远程文件内容:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("my_url");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
String response = client.execute(get,responseHandler);
} catch (Exception e) {
Log.e("RESPONSE", "is "+e.getMessage());
}
解析XML字符串:
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(response));
String value = null;
while(xpp.getEventType() !=XmlPullParser.END_DOCUMENT){ // loop from the beginning to the end of the XML document
if(xpp.getEventType()==XmlPullParser.START_TAG){
if(xpp.getName().equals("version")){
// start tag : <version>
// do some stuff here, like preparing an
// object/variable to recieve the value "1" of the version tag
}
}
else if(xpp.getEventType()==XmlPullParser.END_TAG){
// ... end of the tag: </version> in our example
}
else if(xpp.getEventType()==XmlPullParser.TEXT){ // in a text node
value = xpp.getText(); // here you get the "1" value
}
xpp.next(); // next XPP state
}
答案 1 :(得分:0)
这不是一项特别复杂的任务,在Android开发者网站上会详细介绍here。