2014-02-14 43 views
6

什麼是標準測試元素是否存在與否的方式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 ? 

回答

4

find方法將返回None如果元素不存在。

>>> xml = '''<?xml version="1.0" encoding="utf-8"?> 
... <Test> 
... <MyElement1>sdfsdfdsfd</MyElement1> 
... </Test>''' 
>>> 
>>> from lxml import objectify 
>>> root = objectify.fromstring(xml) 
>>> root.find('.//MyElement1') 
'sdfsdfdsfd' 
>>> root.find('.//MyElement17') 
>>> root.find('.//MyElement17') is None 
True 

根據問題編輯UPDATE

>>> from lxml import objectify 
>>> 
>>> def add_string(parent, attr, s): 
...  if len(attr) == 1: 
...   setattr(parent, attr[0], s) 
...  else: 
...   child = getattr(parent, attr[0], None) 
...   if child is None: 
...    child = objectify.SubElement(parent, attr[0]) 
...   add_string(child, attr[1:], s) 
... 
>>> root = objectify.fromstring(xml) 
>>> add_string(root, ['MyElement1', 'Blah'], 'New') 
>>> add_string(root, ['MyElement17', 'Blah'], 'New') 
>>> add_string(root, ['MyElement1', 'Foo', 'Bar'], 'Hello') 
>>> 
>>> root.MyElement1.Blah 
'New' 
>>> root.MyElement17.Blah 
'New' 
>>> root.MyElement1.Foo.Bar 
'Hello' 
+0

非常感謝。我在問題中增加了第二部分,也許你有一個想法? – Basj

+0

@Basj,我更新了答案。 – falsetru

5

您可以使用getattr

if getattr(root, 'MyElement17', None): 
    # do something 
+3

或'hasattr(根, 'MyElement17')' – falsetru

+0

謝謝!那麼如何寫在一個特定的路徑? (我在問題結尾添加了這個,也許你有一個想法?) – Basj