测试元素是否存在的标准方法是什么lxml.objectify?
示例XML:
<?xml version="1.0" encoding="utf-8"?>
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
</Test>
Run Code Online (Sandbox Code Playgroud)
码
from lxml import etree, objectify
with open('config.xml') as f:
xml = f.read()
root = objectify.fromstring(xml)
print root.MyElement1
print root.MyElement17 # AttributeError: no such child: MyElement17
Run Code Online (Sandbox Code Playgroud)
那么,在特定路径上写一些东西的最简单的解决方案是什么?
root.MyElement1.Blah = 'New' # this works because MyElement1 already exists
root.MyElement17.Blah = 'New' # this doesn't work because MyElement17 doesn't exist
root.MyElement1.Foo.Bar = 'Hello' # this doesn't as well... How to do this shortly ?
Run Code Online (Sandbox Code Playgroud) 使用 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)
但不知道如何获取完整路径的“父”部分。