2012-02-10 11 views
1

xmlファイルを解析するためにcElementTreeを使用しています。 .getroot()関数を使用すると、要素型が結果として返されます。xml.etree.cElementTreeの型要素がif文で認識されない

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 

出力:

<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 

ので

私は、次の操作を行う際に、タイプが認識されない

if type(elementVariable) == 'Element': 
    do stuff 

しかし、if文では、このタイプを使用したいです

print type(rootElement) 

は、 '要素'を型buとします。トン

print type(rootElement) == 'Element' 

がどのようにif文ではそのようなタイプを使用することができます偽与えますか?

+0

あなたは 'elementVariable'という名前を与えたオブジェクトを持っていますが、それはおそらく 'Element'ですか?それはどうですか? –

+2

これはあなたの問題の原因ではありませんが、一般的に 'type(an_object)== a_type'を使った比較は避けてください。代わりに' isinstance(an_object、a_type) 'を使用してください。 http://docs.python.org/library/functions.html#isinstanceをご覧ください。 – lvc

答えて

5

クラスがC実装によって直接公開されていないようです。しかし、あなたはこのトリックを使用することができます:

>>> Element = type(xml.etree.cElementTree.Element(None)) 
>>> root = xml.etree.cElementTree.fromstring('<xml></xml>') 
>>> isinstance(root, Element) 
True 
関連する問題