3

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.

stickfigure
  • 13,458
  • 5
  • 34
  • 50
Jan Pips
  • 113
  • 1
  • 3
  • 11

1 Answers1

4

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)
merlyn
  • 2,273
  • 1
  • 19
  • 26
  • 1
    THANKS!!! That's what I wanted. I knew about the second solution but it is...not so elegant as first one. Nevertheless **thank you** – Jan Pips Nov 06 '18 at 17:04