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

标签 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"

结果是下面的结构

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/

相关文章:

python - 如何捕获python子进程管道执行中的中间错误

python - Pandas 在月初使用 pd.Grouper 进行分组

python - 任何 CPython 2.7 代码都可以在 Jython 2.7b3 中工作吗?

python - 如何使用 Python 的 lxml.objectify 创建非嵌套的 xml 元素?

python-2.7 - lxml - 无法替换 child 的 child

python - 在没有 pytype 的情况下设置值 - lxml objectify

python - 如何从python中的套接字编程中的另一个线程唤醒被select.poll.poll()函数阻塞的线程?

python - numpy 广播如何执行得更快?

python - HTML 抓取 XPath

python - 如何使用 Xpath (lxml) 从多个标签中提取文本?