在XML树的特定路径中写入的较短方式

时间:2014-02-11 22:57:21

标签: python xml xml-parsing elementtree

使用xml.etree.ElementTree,在XML树中的特定路径中写入的较短方法是什么?

我正在寻找这么短的命令:

root = etree.parse('myfile.xml').getroot()   # open an existing XML file
elt = root.element('LocalSettings/MyElement')    # create a node or modify if already exists
elt.text = 'blah'                            # add text

会给出

<?xml version="1.0" ?>
<LocalSettings>
    <MyElement>blah</MyElement>
</LocalSettings>

(PS:我发现的唯一解决方案似乎是更长的代码。)

(PS 2:转到现有路径与elt = root.find('LocalSettings/MyElement')很短)

1 个答案:

答案 0 :(得分:1)

您可以编写create_or_get方法,如果尚不存在,则为您创建路径。类似的东西:

def create_or_get(tree, nodes):
    for node in nodes:
        if not tree.hasElement(node):
            tree.appendChild(tree.createElement(node))
        tree = tree.getElement(node)
    return tree

create_or_get(doc, ["Global", "Config", "Hey"]).text = "lorem ipsum dolor sit amet"