如何将记录保存在xml 文件中?

How to save records in xml file?

在我的网络应用程序中,我想使用 jdom 将记录从数据库 table 保存到 xml 文件,但问题是只保存了一条记录。

Test_xml.java

 List<User> users = session.selectList("dao.UserDao.findAll") ;
for (User u : users) {
       try {

    Element company = new Element("user");
    Document doc = new Document(company);
    Element staff = new Element("data");
     staff.setAttribute(new Attribute("id", u.getId()));
     staff.setAttribute(new Attribute("name", u.getName()));
    doc.getRootElement().addContent(staff);
    XMLOutputter xmlOutput = new XMLOutputter();
    xmlOutput.setFormat(Format.getPrettyFormat());
    xmlOutput.output(doc, new FileWriter("c:\user.xml"));
    out.println("File Saved!");
  } catch (IOException io) {
    out.println(io.getMessage());
  }

我想要这个结构:

<?xml version="1.0" encoding="UTF-8"?>
<user>
<data id="1" name="Nancy" />
<data id="2" name="Jennifer" />
</user>

请帮忙,谢谢。

你一直在覆盖保存的记录。您正在 for 循环中创建新的 XMLOutputer,并使用它将一个用户保存到 user.xml 文件。

因此您的文件将仅包含用户列表中的最后一个用户。

您需要在 for 循环外创建 Root 元素,在循环内附加子节点(代码中的 staff),然后在循环后使用 XMLOutputer 将整个文档输出到 xml.

要拥有这个结构,你可以这样做:

    XMLOutputter xmlOutput = new XMLOutputter();
    Element company = new Element("user");
     Document doc = new Document(company);

    for (User u : users) {
        try {

     Element staff = new Element("data");
     staff.setAttribute(new Attribute("id", u.getId()));
     staff.setAttribute(new Attribute("name", u.getName()));
     doc.getRootElement().addContent(staff);

     xmlOutput.setFormat(Format.getPrettyFormat());
     xmlOutput.output(doc, new FileWriter("c:\user.xml"));

   } catch (IOException io) {
     //@todo manage your exception
   }

}

如果您的 id 是一个整数,您可以这样做:

staff.setAttribute(new Attribute("id",Integer.toString(u.getId())));