Search code examples
javaxml-serializationjaxbxstream

How to Marshall using JAXB (or XStream) to update an XML file without writing the whole file


Just as an example, lets say I have a customerX.xml file that I've unmarshalled using JAXB (or XStream) already.

I update phone number of this customer in my Java object and then marshal the content back to the same customerX.xml

Here's an old jaxb example of xml update, from 2003..There might be a better way though.

Questions

Will marshaling write all contents of the file, though I'm just updating a single element? If yes, then is there a better way to marshal and update a specific element of an XML file using JAXB or XStream?

How do I make a marshalling operation thread safe, in case multiple threads might marshal to the same XML file?


Solution

  • Will marshaling write all contents of the file, though I'm just updating a single element?

    Yes. The marshaller doesn't know or care how much you changed, all it cares about is the state of the objects at the time of marshalling.

    is there a better way to marshal and update a specific element of an XML file using JAXB or XStream?

    Not really. If you need to update fragments of the data, then the data really should be stored as separate files, rather than as one big file.

    How do I make a marshalling operation thread safe, in case multiple threads might marshal to the same XML file?

    Using regular java thread synchronization techniques (i.e. using synchronized methods, or using the locking facilities in java.util.concurrent).