使用python 读取此XML文件,并把读取的到内容写到一个txt文件中;
<info><intro>信息</intro><listid='001'><head>auto_userone</head><name>Jordy</name></lis...
<info>
<intro>信息</intro>
<list id='001'>
<head>auto_userone</head>
<name>Jordy</name>
</list>
</info>
读取结果,如下
信息:
id head
001 auto_userone 展开
<intro>信息</intro>
<list id='001'>
<head>auto_userone</head>
<name>Jordy</name>
</list>
</info>
读取结果,如下
信息:
id head
001 auto_userone 展开
1个回答
展开全部
#vim info.xml
<info>
<intro>信息</intro>
<list id='001'>
<head>auto_userone</head>
<name>Jordy</name>
</list>
</info>
#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
更多追问追答
追问
我运行怎么出错了,求大神指点,俺是新手加菜鸟:Traceback (most recent call last):File "D:/program/python/6-30.py", line 31, in
parse('6-27_1.xml',HeadlineHandler())
我运行怎么出错了,求大神指点,俺是新手加菜鸟:Traceback (most recent call last):File "D:/program/python/6-30.py", line 31, in
parse('6-27_1.xml',HeadlineHandler())
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询