本文介绍了将 XML 资源传递给 XMLReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 .xml 文件从我的 res 文件夹传递到 XMLReader,以便将其解析为一个对象:

I am trying to pass a .xml file from my res folder to an XMLReader in order to parse it to an object:

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.

Could someone guide me to pass this .xml file to the XMLReader.

编辑:

改为:

InputSource inStream = new InputSource(getResources().openRawResource(R.raw.questions));

推荐答案

InputStream inStream = getResources().openRawResource(R.raw.questions);
xr.parse(inStream);

这篇关于将 XML 资源传递给 XMLReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 14:56