How to stream XML data using XOM?

后端 未结 2 2027
无人及你
无人及你 2021-01-03 06:17

Say I want to output a huge set of search results, as XML, into a PrintWriter or an OutputStream, using XOM. The resulting XML would look like this:



        
2条回答
  •  佛祖请我去吃肉
    2021-01-03 06:52

    I ran in to the same issue, but found it's pretty simple to do what you mentioned as an option and subclass Serializer as follows:

    public class StreamSerializer extends Serializer {
    
        public StreamSerializer(OutputStream out) {
            super(out);
        }
    
        @Override
        public void write(Element element) throws IOException {
            super.write(element);
        }
    
        @Override
        public void writeXMLDeclaration() throws IOException {
            super.writeXMLDeclaration();
        }
    
        @Override
        public void writeEndTag(Element element) throws IOException {
            super.writeEndTag(element);
        }
    
        @Override
        public void writeStartTag(Element element) throws IOException {
            super.writeStartTag(element);
        }
    
    }
    

    Then you can still take advantage of the various XOM config like setIdent, etc. but use it like this:

    Element rootElement = new Element("resultset");
    StreamSerializer serializer = new StreamSerializer(out);
    serializer.setIndent(4);
    serializer.writeXMLDeclaration();
    serializer.writeStartTag(rootElement);
    while(hasNextElement()) {
        serializer.write(nextElement());
    }
    serializer.writeEndTag(rootElement);
    serializer.flush();
    

提交回复
热议问题