简体   繁体   中英

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

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM