modification of xml file in java
I have a dialog box that the user inserts various data through gui controls, and this information is saved as an xml file (implemented in java). The information stored in the xml file is configuration information for the application. I can manually modify the xml configuration file, but I also want to provide this capability through a UI as well. So when the dialog is opened (for creation of configuration) a corresponding well-defined object is populated by the various values input by the user. Once the user presses 'save' the information in the object is stored as xml. Now I was thinking to provide the option for edit the file via UI. So the same dialog is displayed to the user, but this time with the configuration information already filled-in by the loaded file. The corresponding object is populated as well. I am not sure what is the best way to modify the file at this point. Should I use 2 objects, 1 that stores all the file's info and 1 that stores the modified values from the dialog, and start comparing the objects for changes so that I modify the file? Or should I delete the file and create a new one? Which is the best approach, and how would I proceed in each?
Consider the data flow. The user will work with the GUI and make changes. The moment they make a modification, the data on the GUI is out of step with the XML. If the user opts to save the data then a simple marshalling operation (trivial if using JAXB) will ensure that the XML is updated. You don't need to compare every field, there's no point - of course you have validated the contents prior to committing them to file. If the user opts to cancel then no marshalling takes place.
There is no need to make a backup and no need to compare what is already in the XML.
However, if the user needs to be able to undo a save (such as revert to previous configuration) then you'll need a backup structure (or maintain a stack of GUI models in memory). I would not recommend that approach, though, as you're just chucking in needless complexity. Users are typically happy with a Save or Cancel button and no Revert.
Keep it simple. Just overwrite the entire file using the updated object. Then you won't need any special code for each case. All you will need is one method to marshall the object into the file and one method to un-marshall it.