lxml.etree 教程2: Elements are lists

>>> 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)
child1
child2
child3

>>> root.insert(0, etree.Element("child0"))
>>> start = root[:1]
>>> end   = root[-1:]

>>> print(start[0].tag)
child0
>>> print(end[0].tag)
child3

  在ElementTree 1.3 和lxml 2.0之前,你可以通过检查一个元素的真值来判断它是否有子节点。例如,是否子节点的链表为空

if root:   # this no longer works!
    print("The root element has children")

  但是这种方式现在不被支持了,因为人们更倾向于某些东西评估为True,期待元素是某些东西。它们有没有子节点等。因此,很多用户会发现这让人惊奇如果任意元素在一个if语句里面被评估为False。取而代之,使用len(element),这更清楚,也不容易犯错。

>>> print(etree.iselement(root))  # test if it's some kind of Element
True
>>> 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)
child0
child1
child2
child3
>>> root[0] = root[-1]  # this moves the element in lxml.etree!
>>> for child in root:
...     print(child.tag)
child3
child1
child2

  在这个例子里面,最后一个元素被移到了其他位置,而不是被复制了。

一个在lxml.etree中的元素只有唯一的父节点,可以使用getparent()方法来获取。

>>> root is root[0].getparent()  # lxml.etree only!
True

  如果你想把一个元素拷贝到到lxml.etree中的其他位置,考虑建立一个独立的深拷贝

>>> 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']

  一个元素的siblings(或邻居)是通过next或previoise方法获取的

>>> root[0] is root[1].getprevious() # lxml.etree only!
True
>>> root[1] is root[0].getnext() # lxml.etree only!
True

  

posted @ 2013-06-09 08:50  小楼  阅读(4424)  评论(0编辑  收藏  举报