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

2024-05-14 11:13:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下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 {} 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

Tags: 实例testnodeasservicecode数字xml
3条回答

使用^{}

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

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

相关问题 更多 >

    热门问题