版权所有,转载请注明出处:http://guangboo.org/2013/01/29/save-chat-history-with-xml
利用上篇文章定义的存储聊天记录的接口,这里具体实现使用xml文件保存聊天记录的功能。
代码如下:
import xml.dom.minidom as dom
import os import datetime
class XmlStorageHistory(History): def __init__(self, jid, to, path): super(XmlStorageHistory, self).__init__(jid, to, path) self.filename = os.path.join(path, to + ".xml") self.doc = None self.root = None self.saved = True def open(self): impl = dom.getDOMImplementation() if os.path.exists(self.filename): self.doc = dom.parse(self.filename) else: self.doc = impl.createDocument(None, 'history', None) self.root = self.doc.documentElement #self.doc.loadxml(parse(self.filename, 'r').read()) self.saved = False def read(self): if self.doc == None or self.root == None: raise HistoryError('Please Open connection.') nodes = self.root.childNodes for node in nodes: yield (node.getAttribute('talk'), node.getAttribute('nick'),\ node.getAttribute('type'), node.nodeValue, node.getAttribute('datetime'),) def write(self, talk, nickname, typ, msg, tm): if self.doc == None or self.root == None: raise HistoryError('Please Open connection.') node = self.doc.createElement('conversation') node.attributes['talk'] = talk node.attributes['nick'] = nickname node.attributes['type'] = typ node.attributes['datetime'] = str(tm) node.appendChild(self.doc.createTextNode(msg)) self.root.appendChild(node) def save(self): stream = open(self.filename, 'w') self.doc.writexml(stream) stream.close() self.saved = True def close(self): if self.saved:return self.save() self.doc = None self.root = None
测试代码同上一篇一致,只是SpliteStorageHistory改成XmlStorageHistory,如下:
if __name__ == '__main__': sql = XmlStorageHistory('zhang@gmail.com','wang2xiao@gmail.com', 'c:\\his2')
sql.open() sql.write('wang2xiao@gmail.com', 'Wang, 2Xiao', 'msg', 'Hi, What are you doing?', datetime.datetime.now()) sql.write('zhang@gmail.com', 'Zhang, Guangbo', 'msg', 'Hi, Nothing.', datetime.datetime.now()) for row in sql.read(): print row sql.close()
测试结果:
('wang2xiao@gmail.com', 'Wang, 2Xiao', 'msg', None, '2013-01-29 23:10:49.937000') ('zhang@gmail.com', 'Zhang, Guangbo', 'msg', None, '2013-01-29 23:10:49.937000')
作者:guangboo 发表于2013-1-29 23:09:11 原文链接
阅读:52 评论:0 查看评论