2012-02-10 5 views
1

xml 파일을 구문 분석하기 위해 cElementTree를 사용하고 있습니다. .getroot() 함수를 사용하면 요소 유형이 결과로 제공됩니다.xml.etree.cElementTree의 Type 요소가 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) 

은 유형으로 '요소'를 제공합니다. t

print type(rootElement) == 'Element' 

어떻게 내가 만약 문에 그런 유형을 사용할 수 있습니다 거짓 준다?

+0

당신은 'elementVariable'이라는 이름을 부여 받았지만 아마도'Element'가 아닌 객체를 가질 수 있습니까? 어떻게 된거 야? –

+2

여기에서는 문제의 원인이 아니지만 일반적으로'type (an_object) == a_type'을 사용하여 비교하지 마십시오. 대신 isinstance (an_object, a_type)를 사용하십시오. http://docs.python.org/library/functions.html#isinstance를 참조하십시오. – lvc

답변

5

Element 클래스가 C 구현에서 직접 노출되지 않는 것처럼 보입니다. 그러나이 속임수를 사용할 수 있습니다 :

>>> Element = type(xml.etree.cElementTree.Element(None)) 
>>> root = xml.etree.cElementTree.fromstring('<xml></xml>') 
>>> isinstance(root, Element) 
True