Search code examples
javaxml-parsingsaxsaxparser

Java Passing Strings to SAX


I'm building a process that creates XML (from a variety of sources and for a variety of purposes that I don't know in advance) and I want to pump the resulting XML directly into standard XML processing like SAX, StAX, and DOM. I've already done a StAX implementation that first produces an XML file and the StAX process reads the file. But I'd really like to skip the intermediate file creation and read. It seems like SAX is the right choice because a push parser is well suited for the job; processing the XML as it becomes available.

I don't quite see how to set up simply passing strings from one Java component into the SAX parser process. Most examples I've found read files and there are some that use URLConnection in support of service type applications. The source in this case will be another Java component that is part of the same system.


Solution

  • A sax parser can read from an InputSource based on a Reader. To feed a string to it, just wrap that string up in a StringReader.

    The code to parse would look something like:

        XMLReader xmlReader = SAXParserFactory.newInstance()
                                .newSAXParser().getXMLReader();
        //Attach content handler, etc...
        InputSource source = new InputSource(new StringReader(xml_string));
        xmlReader.parse(source);
    

    with of course some exception handling that I haven't bothered to show.

    You can do the same in StAX and DOM, though of course the details of where you connect the StringReader are different.