[jdom-interest] Writing on a file stream element by element

Laurent Bihanic laurent.bihanic at atosorigin.com
Thu Oct 4 07:43:50 PDT 2007


 > My problem, instead, is write the new element one by one, everytime that
 > i create it.

I don't think XMLOutputter will let you do that but you can combine 
SAXOuputter with Dave Megginson's XMLWriter/DataWriter 
Use the latter to output the outer document structure (root element) and the 
former to output your data (SAXOutputter.output(Element)).

The twist is to insert an XMLFilter between these two to filter out the 
startDocument and endDocument events generated by each call to 
SAXOuputter.output(Element) that would cause a reset of XMLWriter.

The filter is as simple as :
public class MyFilter extends org.xml.sax.helpers.XMLFilterImpl
    public void startDocument() throws SAXException { }
    public void endDocument() throws SAXException { }

And the code :

MyFilter filter = new MyFilter();
XMLWriter out = new XMLWriter(filter);
SAXOuputter so = new SAXOuputter(filter);



// loop to get JDOM elements
// end loop



NP wrote:
> Hi.
> I have a document so:
> mydoc = new Document();
> a root element:
> rootElement = new Element(....);
> mydoc.setRootElement(rootElement);
> Now i create a new element:
> Element myel = new Element(.....);
> addin' it to the root:
> rootElement.addContent(myel);
> Now i must add the new information (myel) on a file. The code that i 
> wrote was:
> XMLOutputter out = new XMLOutputter(....);
> out.output(mydoc, new File(....));
> But in this way, everytime, i write the whole document in the file 
> (delete file and rewrite the updated document).
> My problem, instead, is write the new element one by one, everytime that 
> i create it.

More information about the jdom-interest mailing list