1

我在创建具有我正在寻找的层次结构的 xml 文档时遇到问题..

<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 没有按我的预期工作,我尝试了其他几个选项,我怎样才能让索赔人元素填充和重复?

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);

谢谢你的帮助 ..

4

1 回答 1

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);
}
于 2012-08-18T23:25:55.937 回答