如果是本地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 中配置允许访问互联网的权限。