使用python 读取此XML文件,并把读取的到内容写到一个txt文件中;

2024-11-01 00:52:14
推荐回答(1个)
回答1:

#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