gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:33 58 4
gpt4 key购买 nike

使用 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"

结果是下面的结构

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

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

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

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

例如元素

config.gui.color.active

我要输入指令

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

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

最佳答案

您可以使用 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()))

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

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)

关于python - 如何获取 lxml.etree._ElementTree 对象的父路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171562/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com