tags:

views:

413

answers:

3

Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (XMLOutputFactory.newInstance().createXMLStreamWriter(...)) for this purpose.

Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. Or is it the only way?

+3  A: 

Simply appending to an XML file will result in malformed XML. You should build the DOM and attach what new elements you need.

Phil
Or if it's a really big file and DOM would blow up memory, use a SAX/STAX/etc. type parser to read it in and write it out to a temp file, append any new data, then copy over the temp file back to the old one.
Marc Novakowski
@PhilThanks.I definitely mean appending 'knowingly', not screwing the schema up.@MarcYeah, that's what I'm currently doing. :)
alex
+1  A: 

Another approach is to build a new XML file and then merge it with the previous one by means of XSLT transformations. To apply XSLT stylesheets you should use Java XML Transformation API.

Fernando Miguélez
+2  A: 

If you're appending a top-level element, you can probably get away with doing what you want. e.g., If you have this file:

<some_element>
  <nested_element>
    ...
  </nested_element>
</some_element>

you can most likely get away with appending another some_element element.

However, you're obviously screwed if there's an outer-level element, and you have to append an inner-level one. For instance, suppose you want to add a some_element element to this file:

<data>
  <some_element>
    <nested_element>
      ...
    </nested_element>
  </some_element>
</data>

In general, you're far better off reparsing the document, then rewriting it. If it's small, use a DOM-based parser; it's easier. If the file is big, then use a SAX-based one.

Brian Clapper