Getting all instances of child node using xml.etree.ElementTree(使用 xml.etree.ElementTree 获取子节点的所有实例)
本文介绍了使用 xml.etree.ElementTree 获取子节点的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下 XML 文件作为输入:
I have the following XML file as input:
<Test>
<callEvents>
<moc>
<causeForTermination>0</causeForTermination>
<serviceCode>
<teleServiceCode>11</teleServiceCode>
</serviceCode>
<dialledDigits>5555555</dialledDigits>
<connectedNumber>77777</connectedNumber>
</moc>
<moc>
<causeForTermination>0</causeForTermination>
<serviceCode>
<teleServiceCode>11</teleServiceCode>
</serviceCode>
<dialledDigits>2222222</dialledDigits>
</moc>
</callEvents>
<callEventsCount>100</callEventsCount>
</Test>
我想输出 dialledDigits 的所有值.但是,我的代码只显示 dialledDigits 的第一个实例.
I want to output all the values for dialledDigits. However, my code only displays the first instance of dialledDigits.
dialledDigits {} 5555555
我想要的输出应该包含这两个实例.
My desired output should contain both instances.
dialledDigits {} 5555555
dialledDigits {} 2222222
这是我的代码
import xml.etree.ElementTree as ET
tree = ET.parse('as.xml')
root = tree.getroot()
callevent=root.find('callEvents')
Moc1=callevent.find('moc')
for node in Moc1.getiterator():
if node.tag=='dialledDigits':
print node.tag, node.attrib, node.text
推荐答案
使用findall
:
moc1 = callevent.findall('moc')
for moc in moc1:
for node in moc.getiterator():
if node.tag=='dialledDigits':
print node.tag, node.attrib, node.text
输出:
dialledDigits {} 5555555
dialledDigits {} 2222222
这篇关于使用 xml.etree.ElementTree 获取子节点的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用 xml.etree.ElementTree 获取子节点的所有实例


基础教程推荐
猜你喜欢
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01