簡體   English   中英

使用xml.etree.ElementTree獲取子節點的所有實例

[英]Getting all instances of child node using xml.etree.ElementTree

我有以下XML文件作為輸入:

<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的第一個實例。

dialledDigits {} 5555555

我想要的輸出應包含兩個實例。

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

您還可以編寫XPath表達式 只有2行而不是5行和一個循環:

for node in tree.findall('.//callEvents/moc/dialledDigits'):
    print node.tag, node.attrib, node.text 

演示:

>>> import xml.etree.ElementTree as ET
>>> 
>>> 
>>> tree = ET.parse('as.xml')
>>> root = tree.getroot()
>>> 
>>> for node in tree.findall('.//callEvents/moc/dialledDigits'):
...     print node.tag, node.attrib, node.text
... 
dialledDigits {} 5555555
dialledDigits {} 2222222

使用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

find()將返回第一個標記對象,因此請使用返回所有標記對象的finadall()

>>> Moc1=callevent.find('moc')
>>> Moc1
<Element 'moc' at 0x869a2ac>
>>> Moc1=callevent.findall('moc')
>>> Moc1
[<Element 'moc' at 0x869a2ac>, <Element 'moc' at 0x869a4ec>]
>>> 

迭代它:

>>> Mocs=callevent.findall('moc')
>>> for moc in Mocs:
...     for node in moc.getiterator():
...         if node.tag=='dialledDigits':
...             print node.tag, node.attrib, node.text
... 
dialledDigits {} 5555555
dialledDigits {} 2222222

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM