什麼是標準測試元素是否存在與否的方式lxml.objectify
?用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 ?
非常感謝。我在問題中增加了第二部分,也許你有一個想法? – Basj
@Basj,我更新了答案。 – falsetru