我有一個網絡應用程序(使用Twisted)接收大塊xml(因爲在整個xml中可能不完整在一個數據包中)通過互聯網。我的思考過程是在收到xml消息時慢慢建立。我已經從xml.etree.ElementTree中解決了iterparse。我已經涉足一些代碼和以下(未加捻的代碼)工作正常:iterparse是拋出'沒有找到元素:第1行,第0列',我不知道爲什麼
import xml.etree.ElementTree as etree
from io import StringIO
buff = StringIO(unicode('<notorious><burger/></notorious>'))
for event, elem in etree.iterparse(buff, events=('end',)):
if elem.tag == 'notorious':
print(etree.tostring(elem))
然後我建立了下面的代碼來模擬數據如何可以在我結束接收:
import xml.etree.ElementTree as etree
from io import StringIO
chunks = ['<notorious>','<burger/>','</notorious>']
buff = StringIO()
for ch in chunks:
buff.write(unicode(ch))
if buff.getvalue() == '<notorious><burger/></notorious>':
print("it should work now")
try:
for event, elem in etree.iterparse(buff, events=('end',)):
if elem.tag == 'notorious':
print(etree.tostring(elem))
except Exception as e:
print(e)
但代碼吐出:
'沒有找到的元素:第1行,第0列'
我無法把頭圍住它。爲什麼第二個示例中的stringIO與第一個代碼示例中stringIO的內容相同時發生該錯誤?
PS:
- 我知道我不是第一個問這個,但沒有其他線程回答我的問題。如果我錯了,請提供相應的線索。
- 如果您有其他模塊的使用建議,請不要將它們放在答案plz中。添加評論。
感謝
Twisted已經在twisted.words中包含了一些解析XMPP的流解析XML內容。你可能想看看http://twistedmatrix.com/documents/current/api/twisted.words.protocols.jabber.xmlstream.XmlStream.html – Glyph 2014-12-05 03:03:41
我知道我試圖重新發明輪子。在我發佈問題之前,我需要找到更好的方法來解析Twisted網站上的所有文檔。生活和學習 – 2014-12-05 15:31:16
聖嬰寶貝jeebus XmlStream你在哪裏我一輩子:D感謝雕文! XmlStream是流式傳輸XML的方式。 – 2014-12-05 15:56:42