Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top