LXML etree檢查我有這樣的XML:的Python如果節點存在
<MasterPage>
<NextPage>
<prefix>
我要檢查,如果prefix
節點存在;我試過了,但沒有奏效:
self.doc=etree.parse(xmlFile)
if hasattr(self.doc, 'MasterPage/NextPage/prefix'):
LXML etree檢查我有這樣的XML:的Python如果節點存在
<MasterPage>
<NextPage>
<prefix>
我要檢查,如果prefix
節點存在;我試過了,但沒有奏效:
self.doc=etree.parse(xmlFile)
if hasattr(self.doc, 'MasterPage/NextPage/prefix'):
您可以使用etree庫中的find()或findall()函數。
當沒有節點時,find()會返回什麼? –
>>> 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']
您的'xml'格式不正確。 – Birei