You are here: > Dive Into Python > Scripts and Streams > Finding direct children of a node | << >> | ||||
Dive Into PythonPython from novice to pro |
Another useful techique when parsing XML documents is finding all the direct child elements of a particular element. For instance, in the grammar files, a ref element can have several p elements, each of which can contain many things, including other p elements. You want to find just the p elements that are children of the ref, not p elements that are children of other p elements.
You might think you could simply use getElementsByTagName for this, but you can't. getElementsByTagName searches recursively and returns a single list for all the elements it finds. Since p elements can contain other p elements, you can't use getElementsByTagName, because it would return nested p elements that you don't want. To find only direct child elements, you'll need to do it yourself.
def randomChildElement(self, node): choices = [e for e in node.childNodes if e.nodeType == e.ELEMENT_NODE]![]()
![]()
chosen = random.choice(choices)
return chosen
<< Caching node lookups | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | | Creating separate handlers by node type >> |