且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在解析之前检查 XML 中是否存在属性和标签?

更新时间:2023-11-26 09:48:40

如果标签不存在,.find() 确实返回 None.只需测试该值:

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')

您已经在事件上使用 .get() 来测试 value 属性;如果属性不存在,它也会返回 None.

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

属性存储在 .attrib 字典中,因此您也可以使用标准 Python 技术来显式测试属性:

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.