简体   繁体   中英

XML parsing Java DOM

So I need to parse an XML that has Multiple choice questions, this is an example question:

XML 示例问题

So I can easily get the Question and the id of the correct answer but I can't seem to be able to get the answers (options). This is the code that I'm using:

            try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(inputFile);

        doc.getDocumentElement().normalize();
        System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
        NodeList nList = doc.getElementsByTagName("Question");
        System.out.println("----------------------------");


        for (int temp = 0; temp < nList.getLength(); temp++) {
            Node nNode = nList.item(temp);
            //System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                Element QuestionElement = (Element) nNode;
                String Question = 
    QuestionElement.getElementsByTagName("text").item(0).getTextContent();
                int answerID = 0;
                try {
                    answerID = Integer.parseInt(QuestionElement.getAttribute("answerid"));
                }
                catch(NumberFormatException e) {
                    System.out.println("Error in parsing Answer ID value for:  " + Question);
                    throw e;
                }

                this.listofQuestions.add(new Question(Question,answerID));

            }
        }


    }
    catch(Exception e) {
        System.out.println("Error in parsing the XML file: " + filename);
        throw e;
    }

Since you're going to store the data in Question and Answer classes anyway, why not let JAXB do the parsing for you?

@XmlRootElement(name = "QuestionBank")
class QuestionBank {
    @XmlElement(name = "Question")
    List<Question> questions;

    @Override
    public String toString() {
        return "QuestionBank" + this.questions;
    }
}
class Question {
    @XmlAttribute
    int id;

    @XmlElement
    String text;

    @XmlAttribute
    int answerid;

    @XmlElementWrapper(name = "answers")
    @XmlElement(name = "option")
    List<Answer> answers;

    @Override
    public String toString() {
        return "Question[id=" + this.id + ", text=" + this.text +
                      ", answerid=" + this.answerid + ", answers=" + this.answers + "]";
    }
}
class Answer {
    @XmlAttribute
    int id;

    @XmlValue
    String text;

    @Override
    public String toString() {
        return this.id + ": " + this.text;
    }
}

Test

QuestionBank questions = (QuestionBank) JAXBContext.newInstance(QuestionBank.class)
        .createUnmarshaller().unmarshal(new File("test.xml"));
System.out.println(questions);

Output

QuestionBank[Question[id=1, text=Who invented the BALLPOINT PEN?, answerid=1, answers=[1: Bito Brothers, 2: Waterman Brothers, 3: Bicc Brothers, 4: Write Brothers]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM