2014-02-16 18 views
0

LXML etree檢查我有這樣的XML:的Python如果節點存在

<MasterPage> 
    <NextPage> 
     <prefix> 

我要檢查,如果prefix節點存在;我試過了,但沒有奏效:

self.doc=etree.parse(xmlFile) 
if hasattr(self.doc, 'MasterPage/NextPage/prefix'): 
+0

您的'xml'格式不正確。 – Birei

回答

0

您可以使用etree庫中的find()或findall()函數。

+0

當沒有節點時,find()會返回什麼? –

1
>>> from lxml.html import fromstring 
>>> import lxml.html as PARSER 
>>> data = """<MasterPage> 
...    <NextPage> 
...     <prefix>""" 
>>> root = PARSER.fromstring(data) 
>>> node_list = [] 
>>> for ele in root.getiterator(): 
...  node_list.append(ele.tag) 
... 
>>> if "prefix" in node_list: 
...  print "True" 
... 
True 
>>> node_list 
['masterpage', 'nextpage', 'prefix'] 
相關問題