是否有任何通过 http 教程或示例读取的工作 xml?
我有一个服务器,其中包含下一行 url: http://192.168.0.1/update.xml
:
<?xml version='1.0' encoding='UTF-8'?>
<Version>1</Version>
我想向 TextView 显示“1”数字。我该怎么做?
这是一段代码,您可以根据自己的需要进行调整:
获取远程文件内容:
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
}
这不是一项特别复杂的任务,在 Android 开发者网站上对此进行了详细介绍。