我正在尝试将.xml
文件从res
文件夹传递到XMLReader
,以便将其解析为对象:
private void parseXML() {
String parsedData = "";
try {
Log.w("AndroidParseXMLActivity", "Start");
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
QuestionXMLHandler myXMLHandler = new QuestionXMLHandler();
xr.setContentHandler(myXMLHandler);
InputSource inStream = new InputSource();
Log.w("AndroidParseXMLActivity", "Parse1");
inStream.setCharacterStream(new StringReader(getResources().getXml(R.xml.questions).toString()));
Log.w("AndroidParseXMLActivity", "Parse2");
xr.parse(inStream);
Log.w("AndroidParseXMLActivity", "Parse3");
ArrayList<QuestionMaster> questionList = myXMLHandler.getQuestionsList();
for(int i=0;i<questionList.size();i++){
QuestionMaster question = questionList.get(i);
parsedData = parsedData + "----->\n";
parsedData = parsedData + "Queston No: " + question.getQuestionNo() + "\n";
parsedData = parsedData + "QuestionText: " + question.getQuestionText() + "\n";
parsedData = parsedData + "CorrectAnswer: " + question.getQuestionText() + "\n";
parsedData = parsedData + "WrongAnswer1: " + question.getQuestionText() + "\n";
parsedData = parsedData + "WrongAnswer2: " + question.getQuestionText() + "\n";
parsedData = parsedData + "WrongAnswer3: " + question.getQuestionText() + "\n";
parsedData = parsedData + "Answered: " + question.isAnswered() + "\n";
parsedData = parsedData + "QuestionText: " + question.isAnsweredCorrectly() + "\n";
}
Log.w("AndroidParseXMLActivity", "Done");
}catch (Exception e) {
Log.w("AndroidParseXMLActivity",e );
}
xmlOutput.setText(parsedData);
}
}
我确信这就是行:
inStream.setCharacterStream(new StringReader(getResources().getXml(R.xml.questions).toString()));
有人可以指导我将此 .xml
文件传递给XMLReader
。
修改:
将其更改为:
InputSource inStream = new InputSource(getResources().openRawResource(R.raw.questions));
答案 0 :(得分:4)
InputStream inStream = getResources().openRawResource(R.raw.questions);
xr.parse(inStream);
答案 1 :(得分:3)
getXml()
会返回XmlPullParser
的实现,因此它已设置为parsed using that engine。将现有代码更改为使用XmlPullParser
而不是SAX。
答案 2 :(得分:0)
我认为您应该将文件放在raw或asset文件夹中以使用SAX解析器,然后使用上下文从那里读取该文件
Android - 从资产中读取文件 http://www.javacodegeeks.com/2012/02/android-read-file-from-assets.html