我正在尝试构建组合的SAX / DOM解析器,它将使用SAX解析器来确定我需要的数据块,并将这些块逐个转发到DOM解析器。 为此,我使用XLMWriter,它使用PipedInputStream / PipedOutputStream将我需要的块写入InputSource:
public class CombinedReaderObserv {
XMLOutputFactory output = null;
XMLStreamWriter writer = null;
PipedOutputStream out;
PipedInputStream in;
InputSource inpSourse;
public CombinedReaderObserv () throws IOException, XMLStreamException {
out = new PipedOutputStream();
in = new PipedInputStream(out);
inpSourse = new InputSource(in);
output = XMLOutputFactory.newInstance();
writer = output.createXMLStreamWriter(out);
}
@Override
public void read(InputStream is) throws Exception {
//Create SAX parser
SAXParserFactory SAXfactory = SAXParserFactory.newInstance();
SAXParser parser = SAXfactory.newSAXParser();
SAXHandler handler = new SAXHandler();
parser.parse(is, handler);
writer.close();
}
private class SAXHandler extends DefaultHandler {
@Override
public void startElement(String URI,
String localName,
String qName,
Attributes attributes) {
try {
//Enables data streaming if found Facility Site starting tag
//element and starts streaming data to the InputSource
switch (qName) {
case "FacilitySite":
write = true;
writer.writeStartDocument();
writer.writeStartElement("root");
default:
if (write == true) {
writer.writeStartElement(qName);
}
}
} catch (XMLStreamException ex) {
ex.printStackTrace();
}
}
@Override
public void endElement(String URI,
String localName,
String qName) {
switch (qName) {
//ends all XML elements and forvardsthe InputSource object
//to parser if found facility site element closing tag
case "FacilitySite":
try {
writer.writeEndElement();
writer.writeEndElement();
writer.writeEndDocument();
reader.read(inpSourse);
writer.flush(); //Program stops here
} catch (Exception ex) {
ex.printStackTrace();
}
write = false;
break;
default:
if (write == true) {
try {
writer.writeEndElement();
} catch (XMLStreamException ex) {
ex.printStackTrace();
}
}
}
}
}
}
问题是在正确解析InputSource对象后,parcer Object继续等待更多输入。 在解析之前关闭XML编写器不会导致任何操作,关闭管道连接会导致“管道关闭”异常。
如何让DOM解析器意识到不再有输入?
更新
从Piped切换到ByteArray Streams帮助。