Next / Previous / Contents / Shipman's homepage

9.2. Accessing the list of child elements

In many ways, an Element instance acts like a Python list, with its XML child elements acting as the members of that list.

You can use the Python len() function to determine how many children an element has. For example, if node is an Element instance with five element children, len(node) will return the value 5.

You can add, replace, or delete children of an element using regular Python list operations. For example, if an Element instance node has three child elements, node[0] is the first child, and node[2] is the third child.

In the examples that follow, assume that E is an Element instance.

Not all children of an element are themselves elements.

If you need to test whether a given child node is a processing instruuction or a comment, you can use Python's built-in function isinstance(I, C), which tests whether an object I is an instance of a class or subclass of class C.

For instance, to test whether node is a comment, you can use this test, which returns True if node is a comment, False otherwise.

issubclass(node, etree._Comment)