我有一个lxml.objectify
从 RESTful Web 服务获得的数据结构。如果存在,我需要更改设置,如果不存在,我需要创建它。现在我有以下内容,但我觉得它很难看。我正在查看的结构有一个子元素列表,它们都具有相同的结构,所以不幸的是我不能只寻找特定的标签。
thing_structure = lxml.objectify(get_from_REST_service())
found_thing = False
if thing_structure.find('settings') is not None:
for i, foo in enumerate(thing_structure.settings):
if foo.is_what_I_want:
modify(thing_structure.settings[i])
found_thing = True
if not found_thing:
new = lxml.etree.SubElement(thing_structure, 'setting')
modify(new)
send_to_REST_service(thing_structure)