我在使用我正在寻找的层次结构创建xml doc时遇到问题。
<claimants>
<claimant>
<Area>Discrimination/Equality</Area>
<Complaints>1</Complaints>
<AssocatedComplaints>3</AssocatedComplaints>
</claimant>
<claimant>
<Area>Redundancy</Area>
<Complaints>1</Complaints>
<AssocatedComplaints>3</AssocatedComplaints>
</claimant>
我得到了这个 -
<claimants>
<claimant>
<Area>Discrimination/Equality</Area>
<Complaints>1</Complaints>
<AssocatedComplaints>3</AssocatedComplaints>
<Area>Redundancy</Area>
<Complaints>1</Complaints>
<AssocatedComplaints>3</AssocatedComplaints>
<Area>Terms and Conditions of Employment</Area>
<Complaints>1</Complaints>
<AssocatedComplaints>3</AssocatedComplaints>
</claimant>
这是代码的相关部分,appendchild不能像我预期的那样工作,我已经尝试了其他几个选项,我怎样才能让claimant元素填充并重复?
Document document = new DocumentImpl();
Element claimants = document.createElement("claimants");
Element claimant = document.createElement("claimant");
... ...
rs = ps.executeQuery();
while (rs.next()) {
// get data in
String area = rs.getString("Area");
System.out.println(">> Area : "+area);
complaints = rs.getString("Complaints");
System.out.println(">> Complaints : "+ complaints);
associated = rs.getString("Associated");
System.out.println(">> Associated : "+associated);
// write text elements
Element eArea = document.createElement("Area");
eArea.appendChild(document.createTextNode(area));
Element eComplaints = document.createElement("Complaints");
eComplaints.appendChild(document.createTextNode(complaints));
Element eAssociated = document.createElement("AssocatedComplaints");
eAssociated.appendChild(document.createTextNode(associated));
// append to claimant
System.out.println("appending ELEMENTS to claimant");
claimant.appendChild(eArea);
claimant.appendChild(eComplaints);
claimant.appendChild(eAssociated);
// append to claimants
System.out.println("appending claimant to claimants");
claimants.appendChild(claimant);
//claimants.insertBefore(claimant, claimants.firstChild);
System.out.println("creating new element claimant");
Element claimant = document.createElement("claimant");
}
document.appendChild(claimants);
感谢您的帮助..
答案 0 :(得分:3)
你需要为每次迭代创建一个新的claimaint
,在循环中:
while (rs.next()) {
Element claimant = document.createElement("claimant"); // a new claimaint is created for each new row
// append elements to claimant
claimant.appendChild(eArea);
claimant.appendChild(eComplaints);
claimant.appendChild(eAssociated);
// append to claimaints
claimants.appendChild(claimant);
}