我有一个XML字符串作为输入,如下所示。对于每个问题,都有多种选择。如何获得每个问题的最高分数?
谢谢。
<root>
<Q>
<QID>1</QID>
<Ans>
<Score>1</Score>
<Choice>Choice 1</Choice>
</Ans>
<Ans>
<Score>2</Score>
<Choice>Choice 2</Choice>
</Ans>
<Ans>
<Score>3</Score>
<Choice>Choice 3</Choice>
</Ans>
</Q>
<Q>
<QID>2</QID>
<Ans>
<Score>10</Score>
<Choice>Choice A</Choice>
</Ans>
<Ans>
<Score>20</Score>
<Choice>Choice B</Choice>
</Ans>
<Ans>
<Score>30</Score>
<Choice>Choice C</Choice>
</Ans>
</Q>
</root>
答案 0 :(得分:0)
如果要计算每个问题的最高分数,可以使用地图:键是问题ID,值是问题最高分数:
Map<Integer, Double> scoreMap = new HashMap<>();
然后,您只需要进行两次迭代,其中外部一个用于问题,而内部一个用于选择和评分:
Map<Integer, Double> scoreMap = new HashMap<>();
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList questions = (NodeList) xpath.evaluate("/root/Q", document, XPathConstants.NODESET);
for (int i = 0; i < questions.getLength(); i++) {
Node question = questions.item(i);
int questionId = Integer.parseInt(xpath.evaluate("QID", question));
System.out.println("question: " + questionId);
NodeList answers = (NodeList) xpath.evaluate("Ans/Score", question, XPathConstants.NODESET);
double maxScore = 0;
for (int j = 0; j < answers.getLength(); j++) {
System.out.println("score: " + answers.item(j).getTextContent());
double score = Double.parseDouble(answers.item(i).getTextContent());
maxScore = Math.max(score, maxScore);
}
scoreMap.put(questionId, maxScore);
}
scoreMap.forEach((k, v) -> System.out.println(k + ": " + v));
它打印:
question: 1
score: 1
score: 2
score: 3
question: 2
score: 10
score: 20
score: 30
1: 1.0
2: 20.0