Home > Blockchain >  Python ElementTree - select element attributes based on value of 1 attribute
Python ElementTree - select element attributes based on value of 1 attribute

Time:07-26

I'm trying to select only 1 element row based on the value of an attribute. For example, in the code below I only want to select the name and age where the title ='President'. How would I go about doing this?

from xml.etree import ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <Report>
        <Element name='Bob' age='32' title='President'></Element>
        <Element name='Sue' age='25' title='Vice-President'></Element>
        <Element name='Mary' age='44' title='Secretary'></Element>
    </Report>'''

root = ET.fromstring(xml)

for target in root.findall('.//*[@title]'):  
    print(target.tag, target.attrib)

CodePudding user response:

You can use an XPath expression to get your Element:

root.find("*[@title='President']")
#          ^ Seach in child elements as well
#           ^ Filter items with a predicate
#            ^ the "title"-attribute must be 'President'

To get your name and age attributes, you can do:

element = root.find("*[@title='President']")
print(element.attrib["name"], element.attrib["age"])

You can find explanation on standard library supported XPath here.

  • Related