1

I have a slight of a problem. I am doing a simple member system over a club. In the system, you should be able to register a new user, and register the users boats. I then save it to a .xml file using JDOM. I have followed a guide in the following site: http://www.journaldev.com/1211/jdom-write-xml-file-example-from-object

The problem is that when a call the method that adds the member in the xml file, it writes a new file. Yes for one time it isn't a problem, but to be able to add members after members even after turning the application off, it will be overwritten and the new member takes the place. This is not what i want.

I want it somehow that every time i add a new member the member gets added at the end of the last added element in the existing xml file, is the no file, then it creates the file or something. Would appreciate help from more experienced guys like you;)

   <?xml version="1.0" encoding="UTF-8"?>
    <Members xmlns="boatclubsystem members">
      <Member xmlns="" memberId="null">
        <name>Jakob Wångö</name>
        <personalID>199107270077</personalID>
        <Boat>
          <boatType>Sailingboat</boatType>
          <boatLenght>30m</boatLenght>
        </Boat>
      </Member>
<Member> xmlns ="memberID="null">
<name>John Doe</name>
</Member>
    </Members>
public class Controller{

    View theView;
    Member memberModel;
    Boat boatModel;
    static String file = "BoatClubSystem.xml";
    static List<Member> memberlist = new ArrayList<Member>();
    static List<Boat> boatlist = new ArrayList<Boat>();

    public static void main(String[]args) throws IOException{
        Member m = new Member();
        Member m2 = new Member();

        Boat b = new Boat();
        Boat b2 = new Boat();


        m.setName("Jakob Wangoe");
        m.setPersonID("19910727****");
        memberlist.add(m);
        b.setBoatType(1);
        b.setBoatLength(30);
        boatlist.add(b);


        createXMLSystem(memberlist, boatlist);
    }

    public static void createXMLSystem(List<Member> memberList, List<Boat> boatlist) throws IOException{ 
        Document doc = new Document(); 
        doc.setRootElement(new Element("Members", 
                Namespace.getNamespace("boatclubsystem members"))); 


        for (Member memb : memberList){ 

                Element member = new Element("Member");
                member.addContent(new Element("memberID").setText(memb.getMemberID()));
                member.addContent(new Element("name").setText(""+memb.getName())); 
                member.addContent(new Element("personalID").setText(memb.getPersonID())); 

            for(Boat boat : boatlist){ 

                Element boats = new Element("Boat"); 
                boats.addContent(new Element("boatType").setText(boat.getBoatType())); 
                boats.addContent(new Element("boatLenght").setText(boat.getBoatLenght()+"m")); 
                member.addContent(boats); 

            } 

                doc.getRootElement().addContent(member); 
        } 

                //JDOM document is ready, write to file  
                XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); 
                xmlOutputter.output(doc, new FileOutputStream(file)); 
    } 
}  
9
  • I think you need to read the file first (if there's any), change it and only after that you should save it again. Commented Oct 8, 2014 at 11:37
  • Check this link journaldev.com/898/how-to-read-an-xml-file-in-java-dom-parser Commented Oct 8, 2014 at 11:39
  • Yes i am looking on that page now actually. But the problem is that i tried combining two examples but didn't work. The guide that i linked uses JDOM 2, but the other example where adding in a existing xml file used another dom Document. So i could understand how to merge those two Commented Oct 8, 2014 at 11:48
  • then try beingjavaguys.com/2013/06/jdom-xml-parser-in-java.html Commented Oct 8, 2014 at 11:52
  • Okey that worked perfect for viewing all members in the xml file. Then i want to add more members, i just came up with an idea, but i don't think it is super effective and may be some resource snatcher. Before i write the new members to the xml file, i load all the Members currently in the file into a List, then i write it all back, the old ones and the newly created member. ? Commented Oct 8, 2014 at 12:22

1 Answer 1

2

JDOM is an in-memory model for XML representation, and the XMLOutputter code dumps the in-memory model to the output (the file on disk).

What you need is to first load the XML in to memory. If the file exists on disk, then load it from file. If the file does not exist, then you have to build an empty one.

The code can become quite complicated to manually build an empty JDOM document. So I have a trick for that, but your basic code block should be:

Document doc = null;
SAXBuilder builder = new SAXBuilder();
if (file.exists()) {
    doc = builder.build(file);
} else {
    // build a fresh document
    ....
}

// build a new member....

....

// add it to the document
Element members = doc.getRootElement();
members.addContent(newMember);

XMLOutputter xmlout = new XMLOutputter(Format.getPrettyFormat());
try (FileOutputStream fos = new FileOutputStream(file)) {
    xmlout.output(fos, doc);
} catch (IOException ...) {
}

A trick I use often for creating empty documents is to use a Jar resource.... and then use that input stream as a seed:

doc = builder.build(ClassLoader.getSystemResource("my/package/EmptyMembers.xml"));

Using the above allows you to edit the empty document as text, instead of building it by components.

Sign up to request clarification or add additional context in comments.

7 Comments

Okey, yes that seems to be the right approach actually. I was thinking of have a empty doc first when build on to it, but could really code it :D Im going to try the trick
One question. What is supposed to be here ? // add it to the document Element members = .... (???) members.addContent(newMember);
Your XML is relatively simple, the members will just be doc.getRootElement(). I have added that to the answer above.
Ahaa. Just as i thought. Okey, i have one small problem, what is the file in file.exists();? ? I Have the following: Document doc = null; SAXBuilder builder = new SAXBuilder(); if (file.exists()) { doc = builder.build(fileName); } else { Document newDoc = new Document(); doc.setRootElement(new Element("Members", Namespace.getNamespace("boatclubsystem members"))); } Shouldn't i instantiate a File file = new File(); ?
Yes, you should have a File instance, or use Files.exists(Paths.get(...))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.