所以我需要解析一个具有多项选择问题的XML,这是一个示例问题:
因此,我可以轻松获得问题和正确答案的ID,但似乎无法获得答案(选项)。这是我正在使用的代码:
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;
}
由于无论如何都要将数据存储在Question
和Answer
类中,为什么不让JAXB为您进行解析?
@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);
输出
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]]]