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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM