3

我正在尝试将.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));
4

3 回答 3

4
InputStream inStream = getResources().openRawResource(R.raw.questions);
xr.parse(inStream);
于 2012-06-12T11:58:59.060 回答
3

getXml()返回 的实现XmlPullParser,因此它已经设置为使用该引擎进行解析。更改现有代码以使用XmlPullParser而不是 SAX。

于 2012-06-12T11:58:16.407 回答
0

我认为您应该将文件放在原始文件夹或资产文件夹中以使用 SAX 解析器,然后使用上下文从那里读取该文件

Android - 从资产 http://www.javacodegeeks.com/2012/02/android-read-file-from-assets.html读取文件

于 2012-06-12T12:01:51.567 回答