Skip to main content

Using JAXB 2.0 to read XML messages off of a network

3 replies [Last post]
spiff
Offline
Joined: 2003-06-10
Points: 0

Hi,

I am trying to read snippets of XML off of an InputStream obtained from a Socket. The behavior I expect is that Unmarshaller.unmarshall(InputStream) will return right after reading the end tag of a root element, allowing me to read multiple objects as they come over the InputStream.

The behavior I am seeing is that Unmarshaller.unmarshal(InputStream) never returns. What I've had to do is read the InputStream into a String until I manually detect the end tag and then give that String to unmarshall (via StringReader).

Is this the expected behavior or a bug? If this is expected behavior, is there some way to get my desired behavior?

P.S. I'm using the 20050407 release. Is there a newer one coming down the pipe or are we expected to build off of CVS now?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kohsuke
Offline
Joined: 2003-06-09
Points: 0

That's the expected behavior of JAXP, which we use to parse XML from a stream.

The XML spec says a parser has to make sure that the only thing that follows the end tag of the root element is whitespaces and comments. Hence a parser has to read until the end of the stream.

The ususal technique to send multiple XML documents across the same socket connection is to write a dummy start tag that will never close, like this:
[code]


...
...

...
[/code]
You can use StAX to nicely parse those individual "documents" into individual JAXB object tree. I think there is a sample that demonstrate the use of StAX.

Take a look at XMPP (http://www.xmpp.org/) and (http://www.faqs.org/rfcs/rfc3920.html) for the actual protocol that uses this mechanism.

spiff
Offline
Joined: 2003-06-10
Points: 0

Thanks, I'll look into StAX.

kohsuke
Offline
Joined: 2003-06-09
Points: 0

I just updated the xml-channel sample in the CVS repository, so if you access it now (or wait for the next Monday's weekly), you'll see how it can be done.