吾知网

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 5637|回复: 0
打印 上一主题 下一主题

android 加载本地、远程xml的方式

[复制链接]
跳转到指定楼层
楼主
发表于 2015-11-20 17:54:05 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

如果是本地xml文件,一般把xml文件放在项目文件夹assets中,程序中代码调用如下




  • InputStream is = null;  
  • AssetManager manager = getAssets();  
  • try  
  • {  
  •     is = manager.open("persons.xml"); //persons.xml保存在assets文件夹下  
  • } catch (IOException e)  
  • {  
  •     e.printStackTrace();  
  • }  


如果是远程xml文件,通过一个http请求返回,则有如下两种方式

方式一:从应用程序发起http




  • InputStream is = null;  
  • AssetManager manager = getAssets();  
  • try  
  • {  
  •     //从应用程序发起http  
  •     String url = "http://xxx.xxxxxx.xxx/service2.asmx/getSaleStates4building?curNum=1";  //远程http地址   
  •     URL myUrl = new URL(url);  
  •     HttpURLConnection conn = (HttpURLConnection)myUrl.openConnection();  
  •     conn.setDoInput(true);  
  •     conn.connect();  
  •     is = conn.getInputStream();  
  • } catch (IOException e)  
  • {  
  •     e.printStackTrace();  
  • }  

方式二:通过Apache API方式





  • InputStream is = null;  
  • AssetManager manager = getAssets();  
  • try  
  • {  
  •     //Apache API 方式  
  •     HttpGet url = new HttpGet("http://xxx.xxxxxx.xxx/service2.asmx/getSaleStates4building?curNum=1");  //远程http地址   
  •     HttpResponse httpResponse = new DefaultHttpClient().execute(url);  
  •     is = httpResponse.getEntity().getContent();  
  • } catch (IOException e)  
  • {  
  •     e.printStackTrace();  
  • }  


以上方式都得到Inputstream,通过android支持的dom、sax、pull三种xml解析方式中的一种来解析获取到的inputstream即可。

当然后两种方式要在AndroidManifest.xml 中配置允许访问互联网的权限。


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|吾知网 ( 粤ICP备13013563号-1 )

GMT+8, 2024-5-17 18:11 , Processed in 1.073284 second(s), 10 queries , Memcache On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表