#vim info.xml
信息
auto_userone
纳扮Jordy
#vim infoxmlparser.py
#!/usr/bin/python
#coding=utf-8
#Python Version Python 2.6.5
from xml.sax.handler import ContentHandler
from xml.sax import parse
class HeadlineHandler(ContentHandler):
in_headline=False
def __init__ (self):
ContentHandler.__init__(self)
self.data=[]
self.file=open('info.txt','w')
self.file.writelines('id'+'\t'+'head\n')
self.file.close()
def startElement(self,name,attrs):
山卖if name == 'list':
self.data.append(attrs['id'])
if name == 'head':
self.in_headline=True
def endElement(self,name):
if name == 'list':
self.file=open('info.txt','a')
self.file.writelines(self.data[0]+'\t'+self.data[1]+'\n')
self.file.close()
self.data=[]
if name == 'head':
self.in_headline=False
def characters(self,string):
if self.in_headline:
self.data.append(string)
if __name__=='__main__':
parse('info.xml',HeadlineHandler())
执行&结果
# python infoxmlparser.py
# cat info.txt
id 逗茄逗head
001 auto_userone