Xml文件保存聊天记录
代码如下:[python]
import xml.dom.minidom as dom<br>import os
import datetime<br>
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,如下:
[python] www.zzzyk.com
if __name__ == '__main__':
sql = <span style="line-height:1.5em">XmlStorageHistory</span><span style="line-height:1.5em">('zhang@gmail.com','wang2xiao@gmail.com', 'c:\\his2')</span><br> 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()
测试结果:
[python]
('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')
补充:Web开发 , Python ,