写XML文件,如何在同一个节点下循环加入多个节点
我写的一段写XML文件的JAVA文件,如下:
public void toWrite(Vector informationV) {
Node first = document.getFirstChild();
String next_id = first.getAttributes().getNamedItem("nextid").getNodevalue();
try{
first.getAttributes().getNamedItem("nextid").setNodevalue(
String.valueOf(Integer.parseInt(next_id) + 1));
Element root = document.createElement("Answerer");
root.setAttribute("id", next_id);
for(int i=0;informationV!=null&&i<informationV.size();i++){
Information information = (Information)informationV.elementAt(i);
Element guessabilityQ = document.createElement("GuessabilityQ");
guessabilityQ.setAttribute("id", String.valueOf(i+1));
Element imageName = document.createElement("ImageName");
imageName.appendChild(document.createTextNode(information.getImageName()));
guessabilityQ.appendChild(imageName);
Element answer = document.createElement("Answer");
answer.appendChild(document.createTextNode(information.getAnswer()));
guessabilityQ.appendChild(answer);
root.appendChild(guessabilityQ);
}catch(Exception e){
e.printStackTrace();
}
}
public void toWrite(Vector informationV) {
Node first = document.getFirstChild();
String next_id = first.getAttributes().getNamedItem("nextid").getNodevalue();
try{
first.getAttributes().getNamedItem("nextid").setNodevalue(
String.valueOf(Integer.parseInt(next_id) + 1));
Element root = document.createElement("Answerer");
root.setAttribute("id", next_id);
for(int i=0;informationV!=null&&i<informationV.size();i++){
Information information = (Information)informationV.elementAt(i);
Element guessabilityQ = document.createElement("GuessabilityQ");
guessabilityQ.setAttribute("id", String.valueOf(i+1));
Element imageName = document.createElement("ImageName");
imageName.appendChild(document.createTextNode(information.getImageName()));
guessabilityQ.appendChild(imageName);
Element answer = document.createElement("Answer");
answer.appendChild(document.createTextNode(information.getAnswer()));
guessabilityQ.appendChild(answer);
root.appendChild(guessabilityQ);
}
first.appendChild(root);}catch(Exception e){
e.printStackTrace();
}
}
加红的部分,我的想法是能循环插入节点,可惜不能成功.
我想生成正确的XML文件如下:
<?xml version="1.0" encoding="GB2312"?>
<Answerers nextid="2">
<Answerer id="1">
<GuessabilityQ id="1">
<ImageName>/ImageTest/question/lihong/GuessabilityTest/image/left.gif</ImageName>
<Answer>f</Answer>
</GuessabilityQ>
<GuessabilityQ id="2">
<ImageName>/ImageTest/question/lihong/GuessabilityTest/image/Y_02.gif</ImageName>
<Answer>f</Answer>
</GuessabilityQ></Answerer>
</Answerers>
兰色部分就是我程序中循环部分想写出的内容,请教我上面JAVA程序应该怎么改才能实现我想要的结果呢