NagyI
NagyI

Reputation: 5997

Parsing a stream of continous XML documents

I have a socket connection for an external system which accept commands and sends results in XML. Every command and result is a standalone XML document.

Which Java parser (/combination) should i use to:

Upvotes: 3

Views: 1611

Answers (3)

helios
helios

Reputation: 13841

Well... XStream.createObjectInputStream seems to be what you need. I'm not sure if the stream provided must enclose all objects into a root node, but anyway you could arrange an inputstreams that add some virtual content to accomodate to XStream needs. I'll expand this answer later...

http://x-stream.github.io/objectstream.html has some samples...

Root node

Indeed the reader needs a root node. So you need an inputstream that reads <object-stream> plus the real byte content, plus a </object-stream> at the end (if you mind about that end). Depending on what you need (inputstream, readers) the implementation can be slighly different but it can be done.

Sample

You can use SequenceInputStream to concatenate virtual content to the original inputstream:

InputStream realOne = ..
// beware of the encoding!
InputStream root = new ByteArrayInputStream("<object-stream>".toBytes("UTF-8")); 
InputStream all = new SequenceInputStream(root, realOne);

xstream.createObjectInputStream(withRoot); // voi lá

If you use readers... well. There must be something equivalent :)

Upvotes: 2

dhblah
dhblah

Reputation: 10151

I'd say you read one full complete response, then parse it. Then read the other. I see no need to continuously read responses.

Upvotes: 0

Aleks G
Aleks G

Reputation: 57316

Your best bet is probably SAX parser. With it, you can implement ContentHandler document and in there, in endDocument method, do the processing and prepare for the next document. Have a look at this page: http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html - for explanation and examples.

Upvotes: 0

Related Questions