好吧,我正在尝试通过套接字连接到一个远程服务器,并且我从套接字返回了大的 xml 响应,由“\n”字符分隔。
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<data>
.......
.......
</data>
</Response>\n <---- \n acts as delimiter
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<data>
....
....
</data>
</Response>\n
..
我正在尝试使用 SAX 解析器解析这些 xml。理想情况下,我想通过搜索 '\n' 获得对字符串的完整响应,并将此响应提供给解析器。但是由于我的单个响应非常大,当我在字符串中保存如此大的 xml 时,我会遇到 outOfMemory 异常。所以剩下的唯一选择是将 xml 流式传输到 SAX。
SAXParserFactory spfactory = SAXParserFactory.newInstance();
SAXParser saxParser = spfactory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(new MyDefaultHandler(context));
InputSource xmlInputSource = new InputSource(new
CloseShieldInputStream(mySocket.getInputStream()));
xmlReader.parse(xmlInputSource);
我正在使用 closeShieldInputStream 来防止 SAX 在出现异常时关闭我的套接字流,因为 '\n'。我问了一个previous question在那..
现在有时我会遇到解析错误
org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 8: not well-formed (invalid token)
我搜索了一下 found当实际 xml 的编码与 SAX 期望的不同时,通常会出现此错误。我写了一个 C 程序并打印出 xml,我所有的 xml 都是用 UTF-8 编码的。
现在我的问题..
- 是否有其他原因导致上述 xml 解析错误 除了编码问题
- 有没有办法打印(或写入任何文件)SAX 的输入为 它从套接字流?
在尝试了 Hemal Pandya 的回答之后..
OutputStream log = new BufferedOutputStream(new FileOutputStream("log.txt"));
InputSource xmlInputSource = new InputSource(new CloseShieldInputStream(new
TeeInputStream(mReadStream, log)));
xmlReader.parse(xmlInputSource);
当我挂载 SDCard 时创建了一个名为 log.txt 的新文件,但它是空的..我用对了吗?
好吧,最后我是怎么做到的..
我用 TeeInputStream 本身解决了这个问题..感谢 Hemal Pandya 的建议..
//open a log file in append mode..
OutputStream log = new BufferedOutputStream(new FileOutputStream("log.txt",true));
InputSource xmlInputSource = new InputSource(new CloseShieldInputStream(new
TeeInputStream(mReadStream, log)));
try{
xmlReader.parse(xmlInputSource);
//flush content in the log stream to file..this code only executes if parsing completed successfully
log.flush();
}catch(SaxException e){
//we want to get the log even if parsing failed..So we are making sure we get the log in either case..
log.flush();
}
最佳答案
Is there any way to print (or write to any file) the input to SAX as it streams from socket?
Apache Commons 有一个 TeeInputStream那应该有用。
OutputStream log = new BufferedOutputStream(new FileOutputtStream("response.xml"));
InputSource xmlInputSource = new InputSource(new
CloseShieldInputStream(new TeeInputStream(mySocket.getInputStream(), log)));
我没用过它,你可能想先在一个独立的程序中尝试它来弄清楚 close
语义,尽管查看文档和你的要求看起来你想要关闭它最后分开。
关于java - 将 xml 输入流式传输到 sax 解析器,如何打印流式传输的 xml?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7646707/