如何获取lxml.etree._ElementTree对象的父路径

Jan*_*ips 3 python lxml lxml.objectify

使用 lxml 库我已经客观化了一些元素(下面的示例代码)

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"
Run Code Online (Sandbox Code Playgroud)

结果是以下结构

config
config.gui
config.gui.color
config.gui.color.active
config.gui.color.readonly
config.gui.color.match
Run Code Online (Sandbox Code Playgroud)

我可以获得每个对象的完整路径

for element in config.iter():
print(element.getroottree().getpath(element))
Run Code Online (Sandbox Code Playgroud)

路径元素由斜杠分隔,但这不是问题。我不知道如何才能只获取路径的父部分,以便我可以使用 setattr 来更改给定元素的值

例如对于元素

config.gui.color.active
Run Code Online (Sandbox Code Playgroud)

我想输入命令

setattr(config.gui.color, 'active', 'something')
Run Code Online (Sandbox Code Playgroud)

但不知道如何获取完整路径的“父”部分。

小智 5

您可以使用该函数获取元素的父元素getparent

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()))
Run Code Online (Sandbox Code Playgroud)

您也可以删除元素路径本身的最后一部分。

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)
Run Code Online (Sandbox Code Playgroud)