When parsing an XML document using xml.etree.ElementTree, you want to find all 'item' tags that are immediate children of the root element. Which method is most efficient for this?
Trap 1: root.iter('item')
iter() searches the entire subtree, not just immediate children.
Trap 2: root.find('item')
find() only returns the first match.
Trap 3: root.get('item')
get() is used for attribute values.
- A
root.findall('item')
findall with a bare tag path matches only direct children of the element it is called on, returning a list in document order. It avoids the recursive descent that './/item' performs, so it is the most efficient way to select immediate children of root.
- B
root.iter('item')
Why it fails: iter() searches the entire subtree, not just immediate children.
- C
root.find('item')
Why it fails: find() only returns the first match.
- D
root.get('item')
Why it fails: get() is used for attribute values.