使用python解析xml不能按预期工作

时间:2017-12-09 01:32:23

标签: python xml parsing

<?xml version="1.0" ?> 
<Data>  
    <Channels>
        <channel0 ChannelName="Name1" />
        <channel1 ChannelName="Name2" />
        <channel2 ChannelName="Name3" />
    </Channels> 
</Data>

出于某种原因,当我从包含上述数据的xml文件中解析它时,我只能打印出channel0 Name1,它会跳过其余的通道。不确定我是否遗漏了某些东西,或者我是否犯了错误。有人可以帮帮我吗?谢谢!

root = et.parse(path).getroot()    
for child in root:    
    for element in child:
        print element.tag, element.attrib['ChannelName']

1 个答案:

答案 0 :(得分:1)

我在Python 3.6中试过这个并打印出所有三个频道

import xml.etree.cElementTree as et

path = 'test.xml'

root = et.parse(path).getroot()    
for child in root:    
    for element in child:
        print(element.tag, element.attrib['ChannelName'])

输出

channel0 Name1
channel1 Name2
channel2 Name3