本文介紹了使用 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 獲取子節點的所有實例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!