Last active
October 21, 2015 16:18
-
-
Save gravesm/ed7012c3d86ba868fc6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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