Two ElementTree questions

M

mirandacascade

1) It appears as if the following logic works for determining whether
an element is a parent:

# assume elem is an ElementTree element
if (elem.getchildren() == None):
print 'this element is not a parent'
else:
print 'this element is a parent'

My question is this: are there any other ways of determining whether an
element is a parent, and if so, are they preferable to the method
above? (I don't have a definition for 'preferable'; I'm hoping the
reply to this question will suggest why a different method may be
preferable.)

2) At one time, I thought I saw some notes indicating that the
getchildren() method will be deprecated. Now, however, I cannot locate
those notes. Has the getchildren() method been deprecated, or will it
be deprecated?
 
F

Fredrik Lundh

1) It appears as if the following logic works for determining whether
an element is a parent:

# assume elem is an ElementTree element
if (elem.getchildren() == None):
print 'this element is not a parent'
else:
print 'this element is a parent'

My question is this: are there any other ways of determining whether an
element is a parent, and if so, are they preferable to the method
above?

if len(elem):
print "is a parent"
else:
print "is not a parent (has no children)"

(in 1.2.X, you can also write "if elem", but that use is discouraged.
see http://effbot.org/zone/element.htm#the-element-type for more
on this).
2) At one time, I thought I saw some notes indicating that the
getchildren() method will be deprecated. Now, however, I cannot locate
those notes. Has the getchildren() method been deprecated, or will it
be deprecated?

an element is a sequence, so there's no need to ever call getchildren
(if you need a real list, use list(elem)).

getchildren() will most likely be removed in some future version of
ElementTree.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
BrentonMcc
Top