[英]XML parsing Java DOM
所以我需要解析一個有多項選擇題的 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
and 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;
}
}
測試
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]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.