سؤال

With xml.etree.ElementTree, what is the shorter way to write in a specific path in the XML tree?

I am looking wheter such a short command exists :

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

which would give

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

(PS : the only solutions I have found seem to be much longer code.)

(PS 2 : going to an existent path is short with elt = root.find('LocalSettings/MyElement') )

هل كانت مفيدة؟

المحلول

You could write a create_or_get method, that creates the path for you if one doesn't already exist. Something like:

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"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top