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

前端 未结 1 1665
野性不改
野性不改 2020-12-13 18:23

I\'m parsing an XML file via Element Tree in python and and writing the content to a cpp file.

The content of children tags will be variant for different tags. For

相关标签:
1条回答
  • 2020-12-13 18:57

    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.
    
    0 讨论(0)
提交回复
热议问题