0

I know Java stax parser works with InputStreams. However, I would need to manually push chunks of strings to the parser instead of inputstream.

Would it be possible?

Kind regards,

adragomir
  • 457
  • 4
  • 16
  • 33
  • If the API doesn't provide methods that accept strings wrap the strings in input streams: [How do I turn a String into a Stream in java?](http://stackoverflow.com/q/247161/637853) – Thomas Mar 29 '16 at 09:53
  • I need to feed continously chucks of strings. So I need to have just 1 xmlinputstream reader, and when I have more chunks of string I need to fetch. – adragomir Mar 29 '16 at 10:00
  • In that case provide your own stream implementation which fetches new chunks in it's `read()` method as needed. – Thomas Mar 29 '16 at 10:02
  • I thought of that. But the read() method only returns an int, which is just 1 char. And my string is a list of chars. How do I feed them? – adragomir Mar 29 '16 at 10:05
  • There are several ways of doing it, e.g. you could delegate to a stream created for one chunk (see linked example or Mena's answer) and if you reach the end of the stream reinit/recreate the delegate stream with a new chunk - or you could have a look at the implementation of some streams (e.g. `ByteArrayInputStream` has a very simple implementation: `return buf[pos++] & 0xff` with `buff` being the result of `String.getBytes(...)`) and mimick it to operate on chunks. – Thomas Mar 29 '16 at 10:08

1 Answers1

0

You can use a ByteArrayInputStream wrapping around your String chunks' bytes.

Quick example

XMLInputFactory factory = XMLInputFactory.newFactory();
XMLStreamReader reader = factory.createXMLStreamReader(
    new ByteArrayInputStream("<start></start>".getBytes("UTF-8"))
);
while (reader.hasNext()) {
    int event = reader.next();
    switch (event) {
    case (XMLStreamConstants.START_ELEMENT): {
        System.out.println(reader.getLocalName());
        break;
    }
    }
}

Output

start
Mena
  • 47,782
  • 11
  • 87
  • 106
  • 1
    I need to feed continously chucks of strings. So I need to have just 1 xmlinputstream reader, and when I have more chunks of string I need to fetch. – adragomir Mar 29 '16 at 10:00