Python:在ElementTree中进行多次打印

时间:2015-08-18 06:10:12

标签: python xml elementtree

我有多个地址和设置名,如下面的xml代码所示:

<Settings>
   <Setting>                  
      <Address>15:0</Address>
      <Comments />
      <Conditions />
      <IsSingleEnded>true</IsSingleEnded>
      <IsVisibilityExternal>false</IsVisibilityExternal>
      <MetaDatas />
      <SettingName>123</SettingName>
   </Setting>
   <Setting>                  
      <Address>18:0</Address>
      <Comments />
      <Conditions />
      <IsSingleEnded>true</IsSingleEnded>
      <IsVisibilityExternal>false</IsVisibilityExternal>
      <MetaDatas />
      <SettingName>abc</SettingName>
   </Setting>
</Settings>

我想打印所有的SettingName和Address。 这是我的代码:

from xml.etree import ElementTree

with open('abc.xml', 'rt') as f:
    tree = ElementTree.parse(f)

    for name in tree.findall('.//SettingName'):
        for address in tree.findall('.//Address'):
            name1 = name.text
            address1 = address.text
            if name1 and address1:
                print name1, address1

最后,它会打印多次设置名称和地址。我想要的是一个设置名称有一个地址,并继续打印,直到完成打印所有设置名称。 我可以知道如何通过我的代码修复它吗?

1 个答案:

答案 0 :(得分:1)

您需要获取所有Setting个节点,然后在其中进行迭代以获取每个设置的每个SettingNameAddress节点并打印它们。示例 -

from xml.etree import ElementTree

with open('BXT_A0_RevF15.xml', 'rt') as f:
    tree = ElementTree.parse(f)

    for setting in tree.findall('.//Setting'):
        address = setting.find('./Address').text
        setting_name = setting.find('./SettingName').text
        if setting_name and address:
            print setting_name , address

如果某些设置可能没有AddressSettingName,那么您还需要通过None检查来考虑这些情况。示例 -

from xml.etree import ElementTree

with open('BXT_A0_RevF15.xml', 'rt') as f:
    tree = ElementTree.parse(f)

    for setting in tree.findall('.//Setting'):
        address = setting.find('./Address')
        setting_name = setting.find('./SettingName')
        if setting_name is not None and address is not None:
            print setting_name.text , address.text