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 is an EElement instance.
returns the child element
of E[i] at
position E, if there is one. If there is no child element at
that position, this operation raises an iIndexError exception.
returns a list of the child elements
between positions E[i:j] and i.
j
For example, node[2:4] returns a list
containing the third and fourth children of node.
You can replace one child of an element with a new
element Ec using a statement of this
form:
E[i] =c
If is
not the position of an existing child, this operation
will raise an iIndexError.
You can replace a sequence of adjacent children of an
element
using slice assignment:
E
E[i:j] =seq
where
is a sequence of seqElement instances.
If the slice [ does not
specify an existing set of children, this operation
will raise an i:j]IndexError exception.
You can delete one child of an element like this:
delE[i]
where
is the index of that child.
i
You can delete a slice out of the list of element children like this:
delE[i:j]
You can iterate over the children of an element
with a for loop. For example, if
node is an Element
instance, this code would print the tags of
all its children:
for kid in node:
print kid.tag
Not all children of an element are themselves elements.
Processing instructions are instances of class etree._ProcessingInstruction.
Comments are instances of class etree._Comment.
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(, which tests whether an object
I, C) is an
instance of a class or subclass of class I.
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)