Skip to content

Instantly share code, notes, and snippets.

@gravesm
Last active October 21, 2015 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gravesm/ed7012c3d86ba868fc6e to your computer and use it in GitHub Desktop.
Save gravesm/ed7012c3d86ba868fc6e to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
>>> root = etree.Element('foo')
>>> el = get_path('bar/baz', root).text = 'foobaz'
>>> etree.tostring(root)
'<foo><bar><baz>foobaz</baz></bar></foo>'
>>> get_path('bar/gaz', root).text = 'foogaz'
>>> etree.tostring(root)
'<foo><bar><baz>foobaz</baz><gaz>foogaz</gaz></bar></foo>'
"""
from functools import reduce
from lxml import etree
def get_path(path, root):
return reduce(get_or_set, path.split('/'), root)
def get_or_set(root, child):
el = root.find(child)
if el is None:
el = etree.SubElement(root, child)
return el
if __name__ == '__main__':
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment