mak_doni
mak_doni

Reputation: 581

How to save records in xml file?

in my web application i want to save records from data base table to xml file by using jdom, but the problem is that just one record is saved.

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

i want to have this structure :

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

Help please,thanks.

Upvotes: 0

Views: 885

Answers (2)

Enjy
Enjy

Reputation: 255

To have this structure you can do:

    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
   }

}

if your id is an int you can do :

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

Upvotes: 0

Zielu
Zielu

Reputation: 8552

You keep overwriting the saved records. You are creating new XMLOutputer inside your for loop, and use it save one user to the user.xml file.

So your file will contain only the last user from the users list.

You need to create the Root element outside the for loop, inside the loop append to it children node (staff in your code), and then after the loop, use XMLOutputer to output the whole document to the xml.

Upvotes: 1

Related Questions