>>> child = root[0]>>> print(child.tag)child1>>> print(len(root))3>>> root.index(root[1]) # lxml.etree only!1>>> children = list(root)>>> for child in root:... print(child.tag)child1child2child3>>> root.insert(0, etree.Element("child0"))>>> start = root[:1]>>> end = root[-1:]>>> print(start[0].tag)child0>>> print(end[0].tag)child3
Before ElementTree 1.3 and lxml 2.0, you can check the true value of an element to determine whether it has subnodes. For example, whether the linked list of a subnode is empty
if root: # this no longer works! print("The root element has children")
However, this method is not supported now, because people prefer to evaluate something as True and expect element to be something. Are there any subnodes. Therefore, many users may find this surprising if any element is evaluated as False in an if statement. Instead, use len (element), which is more clear and not prone to mistakes.
>>> print(etree.iselement(root)) # test if it's some kind of ElementTrue>>> if len(root): # test if it has children... print("The root element has children")The root element has children
>>> for child in root:... print(child.tag)child0child1child2child3>>> root[0] = root[-1] # this moves the element in lxml.etree!>>> for child in root:... print(child.tag)child3child1child2
In this example, the last element is moved to another location, instead of being copied.
An element in lxml. etree has only a unique parent node and can be obtained using the getparent () method.
>>> root is root[0].getparent() # lxml.etree only!True
If you want to copy an element to another location in lxml. etree, create an independent deep copy.
>>> from copy import deepcopy>>> element = etree.Element("neu")>>> element.append( deepcopy(root[1]) )>>> print(element[0].tag)child1>>> print([ c.tag for c in root ])['child3', 'child1', 'child2']
The siblings (or neighbor) of an element is obtained through the next or previise method.
>>> root[0] is root[1].getprevious() # lxml.etree only!True>>> root[1] is root[0].getnext() # lxml.etree only!True