How to get parent path of lxml.etree._ElementTree object

2.1k views Asked by At

Using lxml library I have objectified some elements (sample code below)

config = objectify.Element("config")
gui = objectify.Element("gui")
color = objectify.Element("color")
gui.append(color)
config.append(gui)
config.gui.color.active = "red"
config.gui.color.readonly = "black"
config.gui.color.match = "grey"

the result is the following structure

config
config.gui
config.gui.color
config.gui.color.active
config.gui.color.readonly
config.gui.color.match

I can get a full path for each of the objects

for element in config.iter():
print(element.getroottree().getpath(element))

The path elements are separated by slash but that is not a problem. I do not know how can I get only the parent part of the path so I can use setattr to change the value of given element

For example for element

config.gui.color.active

I would like to enter the command

setattr(config.gui.color, 'active', 'something')

But have no idea how get the "parent" part of full path.

1

There are 1 answers

1
merlyn On BEST ANSWER

You can get the parent of an element using the getparent function.

for element in config.iter():
    print("path:", element.getroottree().getpath(element))
    if element.getparent() is not None:
        print("parent-path:", element.getroottree().getpath(element.getparent()))

You could also just remove the last part of the element path itself.

for element in config.iter():
    path = element.getroottree().getpath(element)
    print("path:", path)
    parts = path.split("/")
    parent_path = "/".join(parts[:-1])
    print("parent-path:", parent_path)