在我的应用程序中,用户可以下载存储在内部存储器中的 XML 文件。有没有办法将这个文件传递给 XMLPullParser 的绝对路径?
问问题
721 次
1 回答
2
由于文件保存在内部,因此您不需要绝对路径,您只需要文件名:
final String xmlFile="fileName";
FileInputStream fis = null;
InputStreamReader isr = null;
char[] inputBuffer = null;
String data = null;
ArrayList<String> items = new ArrayList<String>();
try {
fis = getApplicationContext().openFileInput(xmlFile);
isr = new InputStreamReader(fis);
inputBuffer = new char[fis.available()];
isr.read(inputBuffer);
data = new String(inputBuffer);
isr.close();
fis.close();
} catch (FileNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XmlPullParserFactory factory = null;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try{
xpp.setInput( new StringReader (data) );
} catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int eventType = 0;
try{
eventType = xpp.getEventType();
} catch (XmlPullParserException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
}else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
}else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
}else if(eventType == XmlPullParser.TEXT) {
items.add(xpp.getText());
}
try{
eventType = xpp.next();
}catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String item1=contact.get(0);
String item2=contact.get(1);
String item3 = contact.get(2);
String item4=contact.get(3);
于 2012-12-14T15:49:39.970 回答