lxml.etree 教程6:Tree iteration

來源:互聯網
上載者:User

Elements provide a tree iterator for this purpose. It yields elements in document order, i.e. in the order their tags would appear if you serialised the tree to XML:

>>> root = etree.Element("root")>>> etree.SubElement(root, "child").text = "Child 1">>> etree.SubElement(root, "child").text = "Child 2">>> etree.SubElement(root, "another").text = "Child 3">>> print(etree.tostring(root, pretty_print=True))<root>  <child>Child 1</child>  <child>Child 2</child>  <another>Child 3</another></root>>>> for element in root.iter():...     print("%s - %s" % (element.tag, element.text))root - Nonechild - Child 1child - Child 2another - Child 3

 If you know you are only interested in a single tag, you can pass its name to iter() to have it filter for you. Starting with lxml 3.0, you can also pass more than one tag to intercept on multiple tags during iteration.

>>> for element in root.iter("child"):...     print("%s - %s" % (element.tag, element.text))child - Child 1child - Child 2>>> for element in root.iter("another", "child"):...     print("%s - %s" % (element.tag, element.text))child - Child 1child - Child 2another - Child 3

 By default, iteration yields all nodes in the tree, including ProcessingInstructions, Comments and Entity instances. If you want to make sure only Element objects are returned, you can pass the Element factory as tag parameter:

>>> root.append(etree.Entity("#234"))>>> root.append(etree.Comment("some comment"))>>> for element in root.iter():...     if isinstance(element.tag, basestring):...         print("%s - %s" % (element.tag, element.text))...     else:...         print("SPECIAL: %s - %s" % (element, element.text))root - Nonechild - Child 1child - Child 2another - Child 3SPECIAL: ê - êSPECIAL: <!--some comment--> - some comment>>> for element in root.iter(tag=etree.Element):...     print("%s - %s" % (element.tag, element.text))root - Nonechild - Child 1child - Child 2another - Child 3>>> for element in root.iter(tag=etree.Entity):...     print(element.text)ê

 Note that passing a wildcard "*" tag name will also yield all Element nodes (and only elements).

In lxml.etree, elements provide further iterators for all directions in the tree: children, parents (or rather ancestors) and siblings.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.