if语句中无法识别xml.etree.cElementTree中的Type元素

Nie*_*ein 2 python types if-statement celementtree

我正在使用cElementTree来解析xml文件.使用.getroot()函数提供元素类型作为结果.我想在if语句中使用这种类型

if type(elementVariable) == 'Element':
     do stuff
Run Code Online (Sandbox Code Playgroud)

但是,当我执行以下操作时,无法识别该类型:

import xml.etree.cElementTree as xml
file = 'test.xml'
# parse the xml file into a tree
tree = xml.parse(file)
# Get the root node of the xml file
rootElement = tree.getroot()
return rootElement
print type(rootElement)
print type(rootElement) == 'Element'
print type(rootElement) == Element
Run Code Online (Sandbox Code Playgroud)

输出:

<type 'Element'>
False
Traceback (most recent call last):
  File "/homes/ndeklein/workspace/MS/src/main.py", line 39, in <module>
    print type(rootElement) == Element
NameError: name 'Element' is not defined
Run Code Online (Sandbox Code Playgroud)

所以

print type(rootElement) 
Run Code Online (Sandbox Code Playgroud)

给'元素'作为类型,但是

print type(rootElement) == 'Element' 
Run Code Online (Sandbox Code Playgroud)

假的

如何在if语句中使用类似的类型?

jco*_*ado 6

看起来这个Element类没有被C实现直接暴露.但是你可以使用这个技巧:

>>> Element = type(xml.etree.cElementTree.Element(None))
>>> root = xml.etree.cElementTree.fromstring('<xml></xml>')
>>> isinstance(root, Element)
True
Run Code Online (Sandbox Code Playgroud)