users@jaxb.java.net

Re: Marshalling in chunks?

From: Kohsuke Kawaguchi <Kohsuke.Kawaguchi_at_Sun.COM>
Date: Wed, 17 Aug 2005 17:17:11 -0700

eguy66_at_optonline.net wrote:
> Is my assumption that JAXB 2.0 requires jdk 1.5 correct?

Yes.

> If my above assumption is correct, I'd very much like to see a sample
> SAX XMLFilter, if you can point me to one :) I tried tinkering with
> the generated SAXMarshaller (pass in the printXmlDeclaration value from
> MarshallerImpl) to control the NamespaceContextImpl, without much
> success.

It's probably difficult if you haven't done any SAX programming.

Suppose you want to write:

<envelope>
   <header> ... </header>
   <header> ... </header>
   ...

   <body> ... </body>
   <body> ... </body>
   <body> ... </body>
   ...
</envelope>

where you have numerous huge <body>s so you want to create it and
marshal it one by one.

The idea is to set up the writing process as:

        Marshaller -> YourSAXFilter -> DataWriter

See org.xml.sax.helpers.XMLFilterImpl. By extending it, you can
intercept all the elements that JAXB writes. You can then simply look
for the element where you want to inject the big portion.

You first build the JAXB objects that correspond to:

<envelope>
   <header> ... </header>
   <header> ... </header>
   ...
</envelope>

and then marshal it as shown above. Your XMLFilterImpl would look for
the end element of <envelope>. If it hits one, you goes into the loop
right there.

class MyXMLFilter {
   void endElement(...) {
     if(tagName is "envelope") {
       Marshaller m = create2ndMarshaller();
       enable fragment support with m;
       loop {
         body = createNewBody();
         m.marshal(body,this);
       }
     }
   }
}

The marshal method then marshals a body object to the same filter,
causing the output from <body>s to be merged into DataWriter.

You need to mask the nested start/endDocument events from the 2nd
marshaller, so that DataWriter won't get confused.

-- 
Kohsuke Kawaguchi
Sun Microsystems                   kohsuke.kawaguchi_at_sun.com