问题
I my app creater xml file in Android file system. I ned parse this file with XmlPullParser, but I get error wile compilation: "variable parser might not have been initialized". My code:
InputStream inputStream = openFileInput("settings.xml");
XmlPullParser parser;
parser.setInput(inputStream, null);
Have no idea, how to repair it. I use Intellij IDEA12 and Android 2.3 SDK.
回答1:
I use Eclipse and the below code has worked for me:
You might be missing the below first line:
XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
xppf.setNamespaceAware(true);
XmlPullParser xpp = xppf.newPullParser();
File myXML = new File("myXML.xml"); // give proper path
FileInputStream fis = new FileInputStream(myXML);
xpp.setInput(fis, null);
回答2:
Its working code in eclipes but dont know about Intellij IDEA12
write this code to open and get xml from assets or modify according to your need
try {
XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
XmlPullParser = xppf.newPullParser();
AssetManager manager = context.getResources().getAssets();
InputStream input = manager.open("createDb.xml");
xpp.setInput(input, null);
int type = xpp.getEventType();
while(type != XmlPullParser.END_DOCUMENT) {
if(type == XmlPullParser.START_DOCUMENT) {
Log.d(Tag, "In start document");
}
else if(type == XmlPullParser.START_TAG) {
Log.d(Tag, "In start tag = "+xpp.getName());
}
else if(type == XmlPullParser.END_TAG) {
Log.d(Tag, "In end tag = "+xpp.getName());
}
else if(type == XmlPullParser.TEXT) {
Log.d(Tag, "Have text = "+xpp.getText());
if(xpp.isWhitespace())
{
}
else
{
String strquery = xpp.getText();
db.execSQL(strquery);
}
}
type = xpp.next();
}
}
catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
回答3:
You are not instantiating an instance of XmlPullParser. Try:
XmlPullParser parser = Xml.newPullParser();
Also, you need to call:
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
From the docs:
Use this call to change the general behaviour of the parser, such as namespace processing >or doctype declaration handling. This method must be called before the first call to >next or nextToken. Otherwise, an exception is thrown.
Example: call setFeature(FEATURE_PROCESS_NAMESPACES, true) in order to switch on namespace >processing. The initial settings correspond to the properties requested from the XML Pull >Parser factory. If none were requested, all features are deactivated by default.
来源:https://stackoverflow.com/questions/15698237/xmlpullparser-get-file-from-filesystem