使用xml.etree.ElementTree获取子节点的所有实例

时间:2015-03-25 21:11:29

标签: python xml xml-parsing 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

3 个答案:

答案 0 :(得分:10)

您还可以编写 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

答案 1 :(得分:6)

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

答案 2 :(得分:0)

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