嘗試類似:
import java.util.*;
class Question {
Question(int id, String question) {
this.id = id;
this.question = question;
}
static void toString(Question question, StringBuffer sb, int indent) {
for(int i=0;i<indent;i++)
sb.append('\t');
sb.append(question.id).append(' ').append(question.question).append('\n');
for (Map.Entry<Integer, Answer> entry : question.answers.entrySet()) {
Answer answer = entry.getValue();
for(int i=0;i<=indent;i++)
sb.append('\t');
sb.append(entry.getKey()).append(' ').append(answer.answer).append('\n');
if (answer.question != null) {
toString(answer.question, sb, indent+2);
}
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
toString(this,sb, 0);
return sb.toString();
}
int id;
String question;
SortedMap<Integer, Answer> answers = new TreeMap<Integer, Answer>();
}
class Answer {
Answer(int id, String answer) {
this.id = id;
this.answer = answer;
}
final int id;
final String answer;
Question question; // may be null
}
public class Main {
public static void main(String[] args) {
Question q0 = new Question(0, "What are you looking for?");
Answer a0 = new Answer(0, "table");
q0.answers.put(a0.id, a0);
a0.question = new Question(0, "Which color table you want?");
a0.question.answers.put(0, new Answer(0, "green"));
System.out.println(q0);
}
}
你爲什麼想這樣做? (這可能有助於提供一些想法) – Touko
您可以在http://stackoverflow.com/questions/7231993/how-can-i-parse-the-following-xml-using-jdom問題中看到XML結構,並且我想要解析結構並創建一些數據結構,該數據結構保存xml結構.. –
建議任何想法我應該怎麼做? –