Xml文件保存聊天记录

版权所有,转载请注明出处: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')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值