Java 用SAX解析Android中的XML

Java 用SAX解析Android中的XML,java,android,xml,parsing,sax,Java,Android,Xml,Parsing,Sax,我有一个XML文件,如下所示: <questions title="(Some question Category)"> <question> <ask>(Some question)?</ask> <answer>(Some answer)</answer> <answer correct="true">(Some correct answer)</answer> <answ

我有一个XML文件,如下所示:

<questions title="(Some question Category)">
 <question>
  <ask>(Some question)?</ask>
  <answer>(Some answer)</answer>
  <answer correct="true">(Some correct answer)</answer>
  <answer>(Some answer)</answer>
  <answer>(Some answer)</answer>
 </question>
</questions>


我一直在努力调整,解析XML真的是一项很好的工作。有一个非常好的库,我们可以在Android中轻松使用。它是基于注释的库,有很好的教程。最好的是它直接从XML返回POJO&从性能方面来说,这是好的

您所需要做的就是为XML编写一个基于注释的POJO(请参阅网站上的教程)。使用
serializer.read(pojoClassType,xmlStr)
获取POJO的对象

您还可以使用
Java泛型
概念,只创建一个通用方法来读取每个XML文件。像

public <T> T parseXML(Class<T> pojoType, String xmlStr){
 //your code
} 
public T parseXML(类pojoType,字符串xmlStr){
//你的代码
} 

这就是我如何使用SAX使其工作的

我已经为我的调试示例修改了一个XML文件:

   <game>
    <questions title="History">
        <question>
        <ask>Who won the Battle of Hastings?</ask>
        <answer>Harold Godwinson</answer>
        <answer correct="true">William of Normandy</answer>
        <answer>Edward the Confessor</answer>
        <answer>Harald Hadrada</answer>
        </question>
        <question>
        <ask>French revolution date?</ask>
        <answer>January 10th</answer>
        <answer correct="true">July 14th</answer>
        <answer>September 9th</answer>
        <answer>February 20th</answer>
        </question>
    </questions>
    <questions title="Geography">
        <question>
        <ask>France capital?</ask>
        <answer>Montreal</answer>
        <answer correct="true">Paris</answer>
        <answer>Lyon</answer>
        <answer>Barcelona</answer>
        </question>
    </questions>
</game>
问题

public class Question {

    private String ask;
    private ArrayList<Anserw> alAnserws;

    public Question(){}


    public String getAsk() {
        return ask;
    }

    public void setAsk(String ask) {
        this.ask = ask;
    }

    public ArrayList<Anserw> getAlAnserws() {
        return alAnserws;
    }

    public void setAlAnserws(ArrayList<Anserw> alAnserws) {
        this.alAnserws = alAnserws;
    }


}
public class MyMain {

    /**
     * @param args
     */
    public static void main(String[] args) {


        for(String s : XMLManager.getHmTitleQuestions().keySet()){
            ArrayList<Question> alQuestions = XMLManager.getHmTitleQuestions().get(s);
            ArrayList<Anserw> alAnserws = null;
            System.out.println(s);
            for(Question q:alQuestions){
                System.out.println(q.getAsk());
                alAnserws = q.getAlAnserws();
                for(Anserw a:alAnserws){
                    System.out.println("Content anserw : "+a.getContent()+"/"+a.isCorrect());
                }

            }
        }



    }

}

希望有帮助;-)

我应该说我应该使用SAX——就像我希望使用简单XML这样更简单的选项一样
public class Anserw {

    private String content;
    private boolean isCorrect;

    public Anserw(){}

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public boolean isCorrect() {
        return isCorrect;
    }

    public void setCorrect(boolean isCorrect) {
        this.isCorrect = isCorrect;
    }


}
public class Question {

    private String ask;
    private ArrayList<Anserw> alAnserws;

    public Question(){}


    public String getAsk() {
        return ask;
    }

    public void setAsk(String ask) {
        this.ask = ask;
    }

    public ArrayList<Anserw> getAlAnserws() {
        return alAnserws;
    }

    public void setAlAnserws(ArrayList<Anserw> alAnserws) {
        this.alAnserws = alAnserws;
    }


}
public class QuestionsHandler extends DefaultHandler{

    private HashMap<String, ArrayList<Question>> hmTitleQuestions;
    private String reading;
    private String currentTitle;
    private Question question;
    private ArrayList<Anserw> alAnserws;
    private ArrayList<Question> alQuestions;
    private Anserw anserw;

    public QuestionsHandler(){
        hmTitleQuestions = new HashMap<>();
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        if(qName.equals("questions")){
            currentTitle = attributes.getValue("title");
            alQuestions = new ArrayList<>();
        }
        if(qName.equals("question")){
            question = new Question();
        }
        if(qName.equals("answer")){
            anserw = new Anserw();
            boolean flag = false;
            String correctAttribute = attributes.getValue("correct");
            if(correctAttribute != null){
                if(correctAttribute.equals("true")){
                    flag = true;
                }
            }
            anserw.setCorrect(flag);
        }

    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        if(qName.equals("questions")){
            hmTitleQuestions.put(currentTitle, alQuestions);
        }
        if(qName.equals("question")){
            question.setAlAnserws(alAnserws);
            alQuestions.add(question);
        }
        if(qName.equals("ask")){
            question.setAsk(reading);
            alAnserws = new ArrayList<>();
        }
        if(qName.equals("answer")){
            anserw.setContent(reading);
            alAnserws.add(anserw);
        }

    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        reading = new String(ch, start, length);
    }

    public HashMap<String, ArrayList<Question>> getHmTitleQuestions() {
        return hmTitleQuestions;
    }



}
public final class XMLManager {


    public static HashMap<String, ArrayList<Question>> getHmTitleQuestions(){

        HashMap<String, ArrayList<Question>> hmTitleQuestions = null;
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {

            SAXParser parser = factory.newSAXParser();
            /*
            URL url = new URL("http://www.macs.hw.ac.uk/~pjbk/quiz/example.xml");
            HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
            connexion.connect();
            InputSource in = new InputSource(connexion.getInputStream());
            */
            QuestionsHandler qHandler = new QuestionsHandler();
            /*
             *  FROM INTERNET XML
             * 
                parser.parse(in, qHandler);
                hmTitleQuestions = qHandler.getHmTitleQuestions();


            */

            /*
             *  FROM LOCAL XML TO DEBUG
             */
            File file = new File("D:\\Loic_Workspace\\TestGameSAXUrl\\res\\game.xml");
            parser.parse(file,qHandler);
            hmTitleQuestions = qHandler.getHmTitleQuestions();

        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return hmTitleQuestions;

    }


}
public class MyMain {

    /**
     * @param args
     */
    public static void main(String[] args) {


        for(String s : XMLManager.getHmTitleQuestions().keySet()){
            ArrayList<Question> alQuestions = XMLManager.getHmTitleQuestions().get(s);
            ArrayList<Anserw> alAnserws = null;
            System.out.println(s);
            for(Question q:alQuestions){
                System.out.println(q.getAsk());
                alAnserws = q.getAlAnserws();
                for(Anserw a:alAnserws){
                    System.out.println("Content anserw : "+a.getContent()+"/"+a.isCorrect());
                }

            }
        }



    }

}
History
Who won the Battle of Hastings?
Content anserw : Harold Godwinson/false
Content anserw : William of Normandy/true
Content anserw : Edward the Confessor/false
Content anserw : Harald Hadrada/false
French revolution date?
Content anserw : January 10th/false
Content anserw : July 14th/true
Content anserw : September 9th/false
Content anserw : February 20th/false
Geography
France capital?
Content anserw : Montreal/false
Content anserw : Paris/true
Content anserw : Lyon/false
Content anserw : Barcelona/false