2

我的情况类似于早期关于发出 XML 的问题。我正在分析 SAX ContentHandler 中的数据,同时将其序列化为流。我怀疑链接问题中的解决方案——尽管它正是我在 API 方面正在寻找的解决方案——不是内存效率的,因为它涉及使用 XSLT 处理器的身份转换。我希望程序的内存消耗是有界的,而不是随着输入大小而增长。

如何轻松地将参数转发到我的 ContentHandler 方法到序列化程序,而无需进行杂技以适应例如 StAX 到 SAX,或者更糟糕的是,将 SAX 事件内容复制到输出流?

编辑:这是我所追求的最小示例。thingIWant应该只写入给它的 OutputStream。就像我说的,前面的问题有一个 TransformerHandler,它为我提供了正确的 API,但它使用 XSLT 处理器而不是简单的序列化。

public class MyHandler implements ContentHandler {

    ContentHandler thingIWant;

    MyHandler(OutputStream outputStream) {
        thingIWant = setup(outputStream);
    }

    public void startDocument() throws SAXException {
        // parsing logic
        thingIWant.startDocument();
    }

    public void startElement(String uri, String localName, String qName,
                             Attributes atts) throws SAXException {
        // parsing logic
        thingIWant.startElement(uri, localName, qName, atts);
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        // parsing logic
        thingIWant.characters(ch, start, length);
    }

    // etc...
 }
4

3 回答 3

4

我最近遇到了类似的问题。这是我写给你的东西我想要的课程:

import java.io.OutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.*;

public class XMLSerializer implements ContentHandler {
    static final private TransformerFactory tf = TransformerFactory.newInstance();
    private ContentHandler ch;

    public XMLSerializer(OutputStream os) throws SAXException {
        try {
            final Transformer t = tf.newTransformer();

            t.transform(new SAXSource(                
                new XMLReader() {     
                    public ContentHandler getContentHandler() { return ch; }
                    public DTDHandler getDTDHandler() { return null; }      
                    public EntityResolver getEntityResolver() { return null; }
                    public ErrorHandler getErrorHandler() { return null; }    
                    public boolean getFeature(String name) { return false; }
                    public Object getProperty(String name) { return null; } 
                    public void parse(InputSource input) { }               
                    public void parse(String systemId) { }  
                    public void setContentHandler(ContentHandler handler) { ch = handler; }                
                    public void setDTDHandler(DTDHandler handler) { }
                    public void setEntityResolver(EntityResolver resolver) { }
                    public void setErrorHandler(ErrorHandler handler) { }
                    public void setFeature(String name, boolean value) { }
                    public void setProperty(String name, Object value) { }
                }, new InputSource()),                                    
                new StreamResult(os));
        }
        catch (TransformerException e) {
            throw new SAXException(e);  
        }

        if (ch == null)
            throw new SAXException("Transformer didn't set ContentHandler");
    }

    public void setDocumentLocator(Locator locator) {
        ch.setDocumentLocator(locator);
    }

    public void startDocument() throws SAXException {
        ch.startDocument();
    }

    public void endDocument() throws SAXException {
        ch.endDocument();
    }

    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        ch.startPrefixMapping(prefix, uri);
    }

    public void endPrefixMapping(String prefix) throws SAXException {
        ch.endPrefixMapping(prefix);
    }

    public void startElement(String uri, String localName, String qName, Attributes atts)
        throws SAXException {
        ch.startElement(uri, localName, qName, atts);
    }

    public void endElement(String uri, String localName, String qName)
        throws SAXException {
        ch.endElement(uri, localName, qName);
    }

    public void characters(char[] ch, int start, int length)
        throws SAXException {
        this.ch.characters(ch, start, length);
    }

    public void ignorableWhitespace(char[] ch, int start, int length)
        throws SAXException {
        this.ch.ignorableWhitespace(ch, start, length);
    }

    public void processingInstruction(String target, String data)
        throws SAXException {
        ch.processingInstruction(target, data);
    }

    public void skippedEntity(String name) throws SAXException {
        ch.skippedEntity(name);
    }
}

基本上,它拦截 Transformer 对 parse() 的调用,并获取对其内部 ContentHandler 的引用。之后,该类充当被捕获的 ContentHandler 的代理。

不是很干净,但它的工作原理。

于 2010-02-10T21:09:54.827 回答
3

第一:不用担心身份转换;它不会构建数据的内存表示。

要实现您的“tee”功能,您必须创建一个内容处理程序,该处理程序侦听解析器产生的事件流,并将它们传递给转换器为您提供的处理程序。不幸的是,这并不像听起来那么容易:解析器想要将事件发送到DefaultHandler,而转换器想要从XMLReader读取事件。前者是抽象类,后者是接口。JDK 还提供了类XMLFilterImpl,它实现了 的所有接口DefaultHandler,但没有从它扩展……这就是合并两个不同项目作为“参考实现”的结果。

因此,您需要在两者之间编写一个桥接类:

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLFilterImpl;

/**
 *  Uses a decorator ContentHandler to insert a "tee" into a SAX parse/serialize
 *  stream.
 */
public class SaxTeeExample
{
    public static void main(String[] argv)
    throws Exception
    {
        StringReader src = new StringReader("<root><child>text</child></root>");
        StringWriter dst = new StringWriter();

        Transformer xform = TransformerFactory.newInstance().newTransformer();
        XMLReader reader = new MyReader(SAXParserFactory.newInstance().newSAXParser());
        xform.transform(new SAXSource(reader, new InputSource(src)),
                        new StreamResult(dst));

        System.out.println(dst.toString());
    }


    private static class MyReader
    extends XMLFilterImpl
    {
        private SAXParser _parser;

        public MyReader(SAXParser parser)
        {
            _parser = parser;
        }

        @Override
        public void parse(InputSource input) 
        throws SAXException, IOException
        {
            _parser.parse(input, new XMLFilterBridge(this));
        }

        // this is an example of a "tee" function
        @Override
        public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException
        {
            System.out.println("startElement: " + name);
            super.startElement(uri, localName, name, atts);
        }
    }


    private static class XMLFilterBridge
    extends DefaultHandler
    {
        private XMLFilterImpl _filter;

        public XMLFilterBridge(XMLFilterImpl myFilter)
        {
            _filter = myFilter;
        }

        @Override
        public void characters(char[] ch, int start, int length)
        throws SAXException
        {
            _filter.characters(ch, start, length);
        }

        // override all other methods of DefaultHandler
        // ...
    }
}

main方法设置变压器。有趣的部分是SAXSource是围绕 构建的MyReader。当转换器准备好事件时,它将调用parse()该对象的方法,并传递给它指定的InputSource.

下一部分并不明显:XMLFilterImpl遵循装饰器模式。转换器将在开始转换之前调用此对象的各种 setter 方法,并传递自己的处理程序。我不覆盖的任何方法(例如,startDocument())将简单地调用委托。作为一个示例覆盖,我在startElement(). 您可能会覆盖其他ContentHandler方法。

最后,是和XMLFilterBridge之间的桥梁;它也是一个装饰器,每个方法都简单地调用委托。我展示了一个覆盖,但你必须全部完成。DefaultHandlerXmlReader

于 2009-12-30T19:03:21.880 回答
2

编辑:包括默认的 JDK 版本

最有效的将是XMLWriterwhich implements ContentHandler。简而言之,您正在读写 IO 缓冲区。DOM4J 中有一个XMLWriter,下面正在使用它。您可以子类化XMLWriter或使用XMLFilter 来进行分析。我XMLFilter在这个例子中使用。请注意,这XMLFilter也是一个ContentHandler. 这是完整的代码。

import org.dom4j.io.XMLWriter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.io.PrintStream;

public class XMLPipeline {

    public static void main(String[] args) throws Exception {
        String inputFile = "build.xml";
        PrintStream outputStream = System.out;
        new XMLPipeline().pipe(inputFile, outputStream);
    }

//dom4j
public void pipe(String inputFile, OutputStream outputStream) throws
        SAXException, ParserConfigurationException, IOException {
    XMLWriter xwriter = new XMLWriter(outputStream);
    XMLReader xreader = XMLReaderFactory.createXMLReader();
    XMLAnalyzer analyzer = new XMLAnalyzer(xreader);
    analyzer.setContentHandler(xwriter);
    analyzer.parse(inputFile);

    //do what you want with analyzer
    System.err.println(analyzer.elementCount);
}


//default JDK
public void pipeTrax(String inputFile, OutputStream outputStream) throws
        SAXException, ParserConfigurationException, 
        IOException, TransformerException {
    StreamResult xwriter = new StreamResult(outputStream);
    XMLReader xreader = XMLReaderFactory.createXMLReader();
    XMLAnalyzer analyzer = new XMLAnalyzer(xreader);
    TransformerFactory stf = SAXTransformerFactory.newInstance();
    SAXSource ss = new SAXSource(analyzer, new InputSource(inputFile));
    stf.newTransformer().transform(ss, xwriter);
    System.out.println(analyzer.elementCount);
}

//This method simply reads from a file, runs it through SAX parser and dumps it 
//to dom4j writer
public void dom4jNoop(String inputFile, OutputStream outputStream) throws
        IOException, SAXException {
    XMLWriter xwriter = new XMLWriter(outputStream);
    XMLReader xreader = XMLReaderFactory.createXMLReader();
    xreader.setContentHandler(xwriter);
    xreader.parse(inputFile);

}

//Simplest way to read a file and write it back to an output stream
public void traxNoop(String inputFile, OutputStream outputStream) 
  throws TransformerException {
    TransformerFactory stf = SAXTransformerFactory.newInstance();
    stf.newTransformer().transform(new StreamSource(inputFile), 
     new StreamResult(outputStream));
}    
    //this analyzer counts the number of elements in sax stream
    public static class XMLAnalyzer extends XMLFilterImpl {
        int elementCount = 0;

        public XMLAnalyzer(XMLReader xmlReader) {
            super(xmlReader);
        }

        @Override
        public void startElement(String uri, String localName, String qName, 
          Attributes atts) throws SAXException {
            super.startElement(uri, localName, qName, atts);
            elementCount++;
        }
    }
}
于 2009-12-29T23:30:36.710 回答