Parsing an XML stream with no root element

SequenceInputStream comes to the rescue:

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser parser = saxFactory.newSAXParser();

    parser.parse(
        new SequenceInputStream(
            Collections.enumeration(Arrays.asList(
            new InputStream[] {
                new ByteArrayInputStream("<dummy>".getBytes()),
                new FileInputStream(file),//bogus xml
                new ByteArrayInputStream("</dummy>".getBytes()),
            }))
        ), 
        new DefaultHandler()
    );

You can wrap your given Reader in a FilterReader subclass that you implement to do more or less what you're doing here.

Edit:

While this is similar to the proposal to implement your own Reader delegating to the given Reader object given by a couple other answers, just about all methods in FilterReader would have to be overridden, so you may not gain much from using the superclass.

An interesting variation on the other proposals might be to implement a SequencedReader which wraps multiple Reader objects and shifts to the next in the sequence when one is used up. Then you could pass in a StringReader object with the start text for the root you want to add, the original Reader and another StringReader with the closing tag.


You can write your own Reader-Implementation that encapsulates the Reader-instance you're given. This new Reader should do just what you're doing in your example code, provide the header and root element, then the data from the underlying reader and in the end the closing root tag. By going this way you can provide a valid XML stream to the XML parser and you can as well use the Reader object passed to your code.


Just insert dummy root element. The most elegant solution I can think about is to create your own InputStream or Reader that wraps regular InputSteam/Reader and returns the dummy <dummyroot> when you call its read() / readLine() first time and then returns the result of payload stream. This should satisfy SAX parser.