2

I'm using cElementTree to parse an xml file. Using the .getroot() function gives an element type as result. I want to use this type in an if statement

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

However, the type is not recognized when I do the following:

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

output:

<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

So

print type(rootElement) 

gives 'Element' as type, but

print type(rootElement) == 'Element' 

gives false

How can I use a type like that in an if-statement?

Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • You have an object to which you have given the name 'elementVariable` but it's possibly not an `Element`? How does that happen? – John Machin Feb 10 '12 at 10:48
  • 2
    It isn't the source of your problem here, but in general, avoid comparisons using `type(an_object) == a_type` - use `isinstance(an_object, a_type)` instead. See http://docs.python.org/library/functions.html#isinstance – lvc Feb 10 '12 at 11:05

1 Answers1

6

It looks like the Element class isn't being exposed directly by the C implementation. However you can use this trick:

>>> Element = type(xml.etree.cElementTree.Element(None))
>>> root = xml.etree.cElementTree.fromstring('<xml></xml>')
>>> isinstance(root, Element)
True
jcollado
  • 39,419
  • 8
  • 102
  • 133