测试元素是否存在的标准lxml.objectify
方法是什么?
示例 XML:
<?xml version="1.0" encoding="utf-8"?>
<Test>
<MyElement1>sdfsdfdsfd</MyElement1>
</Test>
代码
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
那么,在特定路径上写东西的最简单解决方案是什么?
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 ?