Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python ElementTree使用条件获取上一个属性_Python_Python 3.x_Elementtree - Fatal编程技术网

Python ElementTree使用条件获取上一个属性

Python ElementTree使用条件获取上一个属性,python,python-3.x,elementtree,Python,Python 3.x,Elementtree,我正在处理XML文件。我的文件是这样的: import xml.etree.ElementTree as ET xml = ''' <root> <a name='name1' label='label1' <b> <result para='1' </b> </a> <a name='name2' label='label2' <b>

我正在处理XML文件。我的文件是这样的:

import xml.etree.ElementTree as ET

xml = '''
<root>
    <a name='name1' label='label1'
      <b>
        <result para='1'
      </b>
    </a>
    <a name='name2' label='label2'
      <b>
        <result para='2'
      </b>
    </a>
    <a name='name3' label='label3'
      <b>
        <result para='3'
      </b>
    </a>
</root>
'''

myroot = ET.fromstring(xml)
但是我不知道如何回到
a
打印标签

任何帮助都将不胜感激:)


提前感谢

按照建议,我将问题向后推,并按如下方式解决:

for type_tag in myroot.findall('a'):
    lab = type_tag.attrib['label']
    for e in type_tag.findall('./b/result'):
        if e.attrib['para'] == '1':
            print(lab)

另一种较短的方法是使用xpath:

for type_tag in myroot.findall('.*//result[@para="1"]/../..'):
    print(type_tag.attrib['label'])

话虽如此,ET只支持xpath的有限子集。因此,如果您有更复杂的xml需要处理,并且可以访问lxml,您应该尝试使用它。

Ok@mkrieger1谢谢您,感谢您的帮助,我成功地解决了我的问题
for type_tag in myroot.findall('.*//result[@para="1"]/../..'):
    print(type_tag.attrib['label'])