How can I check the existence of attributes and tags in XML before parsing? How can I check the existence of attributes and tags in XML before parsing? python python

How can I check the existence of attributes and tags in XML before parsing?


If a tag doesn't exist, .find() indeed returns None. Simply test for that value:

for event in root.findall('event'):    party = event.find('party')    if party is None:        continue    parties = party.text    children = event.get('value')

You already use .get() on event to test for the value the attribute; it returns None as well if the attribute does not exist.

Attributes are stored in the .attrib dictionary, so you can use standard Python techniques to test for the attribute explicitly too:

if 'value' in event.attrib:    # value attribute is present.