[Lxml-checkins] r50160 - in lxml/trunk: . doc
scoder at codespeak.net
scoder at codespeak.net
Fri Dec 28 13:25:31 CET 2007
Author: scoder
Date: Fri Dec 28 13:25:30 2007
New Revision: 50160
Modified:
lxml/trunk/ (props changed)
lxml/trunk/doc/tutorial.txt
Log:
r3188 at delle: sbehnel | 2007-12-28 13:25:12 +0100
tutorial: show how to restrict iteration to Element objects
Modified: lxml/trunk/doc/tutorial.txt
==============================================================================
--- lxml/trunk/doc/tutorial.txt (original)
+++ lxml/trunk/doc/tutorial.txt Fri Dec 28 13:25:30 2007
@@ -328,6 +328,37 @@
child - Child 1
child - Child 2
+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 element.tag, '-', element.text
+ ... else:
+ ... print 'SPECIAL:', element, '-', element.text
+ root - None
+ child - Child 1
+ child - Child 2
+ another - Child 3
+ SPECIAL: ê - ê
+ SPECIAL: <!--some comment--> - some comment
+
+ >>> for element in root.iter(tag=etree.Element):
+ ... print element.tag, '-', element.text
+ root - None
+ child - Child 1
+ child - Child 2
+ another - Child 3
+
+ >>> for element in root.iter(tag=etree.Entity):
+ ... print element.text
+ ê
+
In lxml.etree, elements provide `further iterators`_ for all directions in the
tree: children, parents (or rather ancestors) and siblings.
More information about the lxml-checkins
mailing list