简体   繁体   中英

Shorter way to write in a specific path of the XML tree

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM