find method will return None if the item does not exist.
>>> xml = '''<?xml version="1.0" encoding="utf-8"?> ... <Test> ... <MyElement1>sdfsdfdsfd</MyElement1> ... </Test>''' >>> >>> from lxml import objectify >>> root = objectify.fromstring(xml) >>> root.find('.//MyElement1') 'sdfsdfdsfd' >>> root.find('.//MyElement17') >>> root.find('.//MyElement17') is None True
UPDATE according to the question:
>>> from lxml import objectify >>> >>> def add_string(parent, attr, s): ... if len(attr) == 1: ... setattr(parent, attr[0], s) ... else: ... child = getattr(parent, attr[0], None) ... if child is None: ... child = objectify.SubElement(parent, attr[0]) ... add_string(child, attr[1:], s) ... >>> root = objectify.fromstring(xml) >>> add_string(root, ['MyElement1', 'Blah'], 'New') >>> add_string(root, ['MyElement17', 'Blah'], 'New') >>> add_string(root, ['MyElement1', 'Foo', 'Bar'], 'Hello') >>> >>> root.MyElement1.Blah 'New' >>> root.MyElement17.Blah 'New' >>> root.MyElement1.Foo.Bar 'Hello'
source share