嗯,我試圖通過套接字連接到一個遠程服務器,並從套接字返回大的XML響應,由'\ n'字符分隔。流xml輸入到薩克斯解析器,如何打印xml流?
<?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
..
我想解析這些XML使用SAX解析器。理想情況下,我希望通過搜索'\ 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作爲 它從套接字流?
試圖血管潘迪亞的回答後..
OutputStream log = new BufferedOutputStream(new FileOutputStream("log.txt"));
InputSource xmlInputSource = new InputSource(new CloseShieldInputStream(new
TeeInputStream(mReadStream, log)));
xmlReader.parse(xmlInputSource);
的log.txt得到它empty..Am我使用這一權利創造了名的新文件,當我安裝SD卡,但?
那麼最後我是怎麼做到的..
我TeeInputStream工作了itself..thanks血管潘迪亞的提示..
//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();
}
請參閱我的編輯,我已經爲每個響應添加了一個doctype元素。是否是第一個錯誤的原因? – Krishnabhadra
不是在'try'和'catch'塊中都調用'log.flush()',而是另外一個選項是這樣做:嘗試xmlReader.parse(xmlInputSource); } catch(SaxException e){*} log exception */ } log.flush(); ' –
hmmm ...但在我的情況下,當我有一個異常,我從異常捕獲本身返回正確的..所以這是不可能在我的情況下 – Krishnabhadra