Sophie

Sophie

distrib > CentOS > 5 > i386 > by-pkgid > 90dba77ca23efa667b541b5c0dd77497 > files > 394

python-lxml-2.0.11-2.el5.i386.rpm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
<title>The lxml.etree Tutorial</title>
<meta name="author" content="Stefan Behnel" />
<meta content="The lxml tutorial on XML that feels like Python" name="description" />
<meta content="lxml, etree, tutorial, ElementTree, Python, XML, HTML" name="keywords" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="document" id="the-lxml-etree-tutorial">
<div class="sidemenu"><ul id="lxml"><li><span class="section title">lxml</span><ul class="menu foreign" id="index"><li class="menu title"><a href="index.html">lxml</a><ul class="submenu"><li class="menu item"><a href="index.html#introduction">Introduction</a></li><li class="menu item"><a href="index.html#documentation">Documentation</a></li><li class="menu item"><a href="index.html#download">Download</a></li><li class="menu item"><a href="index.html#mailing-list">Mailing list</a></li><li class="menu item"><a href="index.html#bug-tracker">Bug tracker</a></li><li class="menu item"><a href="index.html#license">License</a></li><li class="menu item"><a href="index.html#old-versions">Old Versions</a></li></ul></li></ul><ul class="menu foreign" id="intro"><li class="menu title"><a href="intro.html">Why lxml?</a><ul class="submenu"><li class="menu item"><a href="intro.html#motto">Motto</a></li><li class="menu item"><a href="intro.html#aims">Aims</a></li></ul></li></ul><ul class="menu foreign" id="installation"><li class="menu title"><a href="installation.html">Installing lxml</a><ul class="submenu"><li class="menu item"><a href="installation.html#requirements">Requirements</a></li><li class="menu item"><a href="installation.html#installation">Installation</a></li><li class="menu item"><a href="installation.html#building-lxml-from-sources">Building lxml from sources</a></li><li class="menu item"><a href="installation.html#ms-windows">MS Windows</a></li><li class="menu item"><a href="installation.html#macos-x">MacOS-X</a></li></ul></li></ul><ul class="menu foreign" id="lxml2"><li class="menu title"><a href="lxml2.html">What's new in lxml 2.0?</a><ul class="submenu"><li class="menu item"><a href="lxml2.html#changes-in-etree-and-objectify">Changes in etree and objectify</a></li><li class="menu item"><a href="lxml2.html#new-modules">New modules</a></li></ul></li></ul><ul class="menu foreign" id="performance"><li class="menu title"><a href="performance.html">Benchmarks and Speed</a><ul class="submenu"><li class="menu item"><a href="performance.html#general-notes">General notes</a></li><li class="menu item"><a href="performance.html#how-to-read-the-timings">How to read the timings</a></li><li class="menu item"><a href="performance.html#parsing-and-serialising">Parsing and Serialising</a></li><li class="menu item"><a href="performance.html#the-elementtree-api">The ElementTree API</a></li><li class="menu item"><a href="performance.html#xpath">XPath</a></li><li class="menu item"><a href="performance.html#a-longer-example">A longer example</a></li><li class="menu item"><a href="performance.html#lxml-objectify">lxml.objectify</a></li></ul></li></ul><ul class="menu foreign" id="compatibility"><li class="menu title"><a href="compatibility.html">ElementTree compatibility of lxml.etree</a></li></ul><ul class="menu foreign" id="FAQ"><li class="menu title"><a href="FAQ.html">lxml FAQ - Frequently Asked Questions</a><ul class="submenu"><li class="menu item"><a href="FAQ.html#general-questions">General Questions</a></li><li class="menu item"><a href="FAQ.html#installation">Installation</a></li><li class="menu item"><a href="FAQ.html#contributing">Contributing</a></li><li class="menu item"><a href="FAQ.html#bugs">Bugs</a></li><li class="menu item"><a href="FAQ.html#threading">Threading</a></li><li class="menu item"><a href="FAQ.html#parsing-and-serialisation">Parsing and Serialisation</a></li><li class="menu item"><a href="FAQ.html#xpath-and-document-traversal">XPath and Document Traversal</a></li></ul></li></ul></li></ul><ul id="Developing with lxml"><li><span class="section title">Developing with lxml</span><ul class="menu current" id="tutorial"><li class="menu title"><a href="tutorial.html">The lxml.etree Tutorial</a><ul class="submenu"><li class="menu item"><a href="tutorial.html#the-element-class">The Element class</a></li><li class="menu item"><a href="tutorial.html#the-elementtree-class">The ElementTree class</a></li><li class="menu item"><a href="tutorial.html#parsing-from-strings-and-files">Parsing from strings and files</a></li><li class="menu item"><a href="tutorial.html#namespaces">Namespaces</a></li><li class="menu item"><a href="tutorial.html#the-e-factory">The E-factory</a></li><li class="menu item"><a href="tutorial.html#elementpath">ElementPath</a></li></ul></li></ul><ul class="menu foreign" id="api index"><li class="menu title"><a href="api/index.html">API reference</a></li></ul><ul class="menu foreign" id="api"><li class="menu title"><a href="api.html">APIs specific to lxml.etree</a><ul class="submenu"><li class="menu item"><a href="api.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="api.html#other-element-apis">Other Element APIs</a></li><li class="menu item"><a href="api.html#trees-and-documents">Trees and Documents</a></li><li class="menu item"><a href="api.html#iteration">Iteration</a></li><li class="menu item"><a href="api.html#error-handling-on-exceptions">Error handling on exceptions</a></li><li class="menu item"><a href="api.html#error-logging">Error logging</a></li><li class="menu item"><a href="api.html#serialisation">Serialisation</a></li><li class="menu item"><a href="api.html#xinclude-and-elementinclude">XInclude and ElementInclude</a></li><li class="menu item"><a href="api.html#write-c14n-on-elementtree">write_c14n on ElementTree</a></li></ul></li></ul><ul class="menu foreign" id="parsing"><li class="menu title"><a href="parsing.html">Parsing XML and HTML with lxml</a><ul class="submenu"><li class="menu item"><a href="parsing.html#parsers">Parsers</a></li><li class="menu item"><a href="parsing.html#the-target-parser-interface">The target parser interface</a></li><li class="menu item"><a href="parsing.html#the-feed-parser-interface">The feed parser interface</a></li><li class="menu item"><a href="parsing.html#iterparse-and-iterwalk">iterparse and iterwalk</a></li><li class="menu item"><a href="parsing.html#python-unicode-strings">Python unicode strings</a></li></ul></li></ul><ul class="menu foreign" id="validation"><li class="menu title"><a href="validation.html">Validation with lxml</a><ul class="submenu"><li class="menu item"><a href="validation.html#validation-at-parse-time">Validation at parse time</a></li><li class="menu item"><a href="validation.html#dtd">DTD</a></li><li class="menu item"><a href="validation.html#relaxng">RelaxNG</a></li><li class="menu item"><a href="validation.html#xmlschema">XMLSchema</a></li><li class="menu item"><a href="validation.html#schematron">Schematron</a></li></ul></li></ul><ul class="menu foreign" id="xpathxslt"><li class="menu title"><a href="xpathxslt.html">XPath and XSLT with lxml</a><ul class="submenu"><li class="menu item"><a href="xpathxslt.html#xpath">XPath</a></li><li class="menu item"><a href="xpathxslt.html#xslt">XSLT</a></li></ul></li></ul><ul class="menu foreign" id="objectify"><li class="menu title"><a href="objectify.html">lxml.objectify</a><ul class="submenu"><li class="menu item"><a href="objectify.html#the-lxml-objectify-api">The lxml.objectify API</a></li><li class="menu item"><a href="objectify.html#asserting-a-schema">Asserting a Schema</a></li><li class="menu item"><a href="objectify.html#objectpath">ObjectPath</a></li><li class="menu item"><a href="objectify.html#python-data-types">Python data types</a></li><li class="menu item"><a href="objectify.html#how-data-types-are-matched">How data types are matched</a></li><li class="menu item"><a href="objectify.html#what-is-different-from-lxml-etree?">What is different from lxml.etree?</a></li></ul></li></ul><ul class="menu foreign" id="lxmlhtml"><li class="menu title"><a href="lxmlhtml.html">lxml.html</a><ul class="submenu"><li class="menu item"><a href="lxmlhtml.html#parsing-html">Parsing HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-element-methods">HTML Element Methods</a></li><li class="menu item"><a href="lxmlhtml.html#running-html-doctests">Running HTML doctests</a></li><li class="menu item"><a href="lxmlhtml.html#creating-html-with-the-e-factory">Creating HTML with the E-factory</a></li><li class="menu item"><a href="lxmlhtml.html#working-with-links">Working with links</a></li><li class="menu item"><a href="lxmlhtml.html#forms">Forms</a></li><li class="menu item"><a href="lxmlhtml.html#cleaning-up-html">Cleaning up HTML</a></li><li class="menu item"><a href="lxmlhtml.html#html-diff">HTML Diff</a></li><li class="menu item"><a href="lxmlhtml.html#examples">Examples</a></li></ul></li></ul><ul class="menu foreign" id="cssselect"><li class="menu title"><a href="cssselect.html">lxml.cssselect</a><ul class="submenu"><li class="menu item"><a href="cssselect.html#the-cssselector-class">The CSSSelector class</a></li><li class="menu item"><a href="cssselect.html#css-selectors">CSS Selectors</a></li><li class="menu item"><a href="cssselect.html#limitations">Limitations</a></li></ul></li></ul><ul class="menu foreign" id="elementsoup"><li class="menu title"><a href="elementsoup.html">BeautifulSoup Parser</a><ul class="submenu"><li class="menu item"><a href="elementsoup.html#entity-handling">Entity handling</a></li><li class="menu item"><a href="elementsoup.html#using-soupparser-as-a-fallback">Using soupparser as a fallback</a></li></ul></li></ul></li></ul><ul id="Extending lxml"><li><span class="section title">Extending lxml</span><ul class="menu foreign" id="resolvers"><li class="menu title"><a href="resolvers.html">Document loading and URL resolving</a><ul class="submenu"><li class="menu item"><a href="resolvers.html#resolvers">Resolvers</a></li><li class="menu item"><a href="resolvers.html#document-loading-in-context">Document loading in context</a></li><li class="menu item"><a href="resolvers.html#i-o-access-control-in-xslt">I/O access control in XSLT</a></li></ul></li></ul><ul class="menu foreign" id="extensions"><li class="menu title"><a href="extensions.html">Extension functions for XPath and XSLT</a><ul class="submenu"><li class="menu item"><a href="extensions.html#the-functionnamespace">The FunctionNamespace</a></li><li class="menu item"><a href="extensions.html#global-prefix-assignment">Global prefix assignment</a></li><li class="menu item"><a href="extensions.html#the-xpath-context">The XPath context</a></li><li class="menu item"><a href="extensions.html#evaluators-and-xslt">Evaluators and XSLT</a></li><li class="menu item"><a href="extensions.html#evaluator-local-extensions">Evaluator-local extensions</a></li><li class="menu item"><a href="extensions.html#what-to-return-from-a-function">What to return from a function</a></li></ul></li></ul><ul class="menu foreign" id="element classes"><li class="menu title"><a href="element_classes.html">Using custom Element classes in lxml</a><ul class="submenu"><li class="menu item"><a href="element_classes.html#element-initialization">Element initialization</a></li><li class="menu item"><a href="element_classes.html#setting-up-a-class-lookup-scheme">Setting up a class lookup scheme</a></li><li class="menu item"><a href="element_classes.html#implementing-namespaces">Implementing namespaces</a></li></ul></li></ul><ul class="menu foreign" id="sax"><li class="menu title"><a href="sax.html">Sax support</a><ul class="submenu"><li class="menu item"><a href="sax.html#building-a-tree-from-sax-events">Building a tree from SAX events</a></li><li class="menu item"><a href="sax.html#producing-sax-events-from-an-elementtree-or-element">Producing SAX events from an ElementTree or Element</a></li><li class="menu item"><a href="sax.html#interfacing-with-pulldom-minidom">Interfacing with pulldom/minidom</a></li></ul></li></ul><ul class="menu foreign" id="capi"><li class="menu title"><a href="capi.html">The public C-API of lxml.etree</a><ul class="submenu"><li class="menu item"><a href="capi.html#writing-external-modules-in-cython">Writing external modules in Cython</a></li><li class="menu item"><a href="capi.html#writing-external-modules-in-c">Writing external modules in C</a></li></ul></li></ul></li></ul><ul id="Developing lxml"><li><span class="section title">Developing lxml</span><ul class="menu foreign" id="build"><li class="menu title"><a href="build.html">How to build lxml from source</a><ul class="submenu"><li class="menu item"><a href="build.html#cython">Cython</a></li><li class="menu item"><a href="build.html#subversion">Subversion</a></li><li class="menu item"><a href="build.html#setuptools">Setuptools</a></li><li class="menu item"><a href="build.html#running-the-tests-and-reporting-errors">Running the tests and reporting errors</a></li><li class="menu item"><a href="build.html#contributing-an-egg">Contributing an egg</a></li><li class="menu item"><a href="build.html#providing-newer-library-versions-on-mac-os-x">Providing newer library versions on Mac-OS X</a></li><li class="menu item"><a href="build.html#static-linking-on-windows">Static linking on Windows</a></li><li class="menu item"><a href="build.html#building-debian-packages-from-svn-sources">Building Debian packages from SVN sources</a></li></ul></li></ul><ul class="menu foreign" id="lxml source howto"><li class="menu title"><a href="lxml-source-howto.html">How to read the source of lxml</a><ul class="submenu"><li class="menu item"><a href="lxml-source-howto.html#what-is-cython?">What is Cython?</a></li><li class="menu item"><a href="lxml-source-howto.html#where-to-start?">Where to start?</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-etree">lxml.etree</a></li><li class="menu item"><a href="lxml-source-howto.html#python-modules">Python modules</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-objectify">lxml.objectify</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-pyclasslookup">lxml.pyclasslookup</a></li><li class="menu item"><a href="lxml-source-howto.html#lxml-html">lxml.html</a></li></ul></li></ul><ul class="menu foreign" id="changes 2 0 11"><li class="menu title"><a href="changes-2.0.11.html">Release Changelog</a></li></ul><ul class="menu foreign" id="credits"><li class="menu title"><a href="credits.html">Credits</a><ul class="submenu"><li class="menu item"><a href="credits.html#special-thanks-goes-to:">Special thanks goes to:</a></li></ul></li></ul></li></ul></div><h1 class="title">The lxml.etree Tutorial</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>Stefan Behnel</td></tr>
</tbody>
</table>
<p>This tutorial briefly overviews the main concepts of the <a class="reference" href="http://effbot.org/zone/element-index.htm#documentation">ElementTree API</a> as
implemented by <tt class="docutils literal"><span class="pre">lxml.etree</span></tt>, and some simple enhancements that make your
life as a programmer easier.</p>
<p>For a complete reference of the API, see the <a class="reference" href="api/index.html">generated API
documentation</a>.</p>
<div class="contents topic">
<p class="topic-title first"><a id="contents" name="contents">Contents</a></p>
<ul class="simple">
<li><a class="reference" href="#the-element-class" id="id2" name="id2">The Element class</a><ul>
<li><a class="reference" href="#elements-are-lists" id="id3" name="id3">Elements are lists</a></li>
<li><a class="reference" href="#elements-carry-attributes" id="id4" name="id4">Elements carry attributes</a></li>
<li><a class="reference" href="#elements-contain-text" id="id5" name="id5">Elements contain text</a></li>
<li><a class="reference" href="#using-xpath-to-find-text" id="id6" name="id6">Using XPath to find text</a></li>
<li><a class="reference" href="#tree-iteration" id="id7" name="id7">Tree iteration</a></li>
<li><a class="reference" href="#serialisation" id="id8" name="id8">Serialisation</a></li>
</ul>
</li>
<li><a class="reference" href="#the-elementtree-class" id="id9" name="id9">The ElementTree class</a></li>
<li><a class="reference" href="#parsing-from-strings-and-files" id="id10" name="id10">Parsing from strings and files</a><ul>
<li><a class="reference" href="#the-fromstring-function" id="id11" name="id11">The fromstring() function</a></li>
<li><a class="reference" href="#the-xml-function" id="id12" name="id12">The XML() function</a></li>
<li><a class="reference" href="#the-parse-function" id="id13" name="id13">The parse() function</a></li>
<li><a class="reference" href="#parser-objects" id="id14" name="id14">Parser objects</a></li>
<li><a class="reference" href="#incremental-parsing" id="id15" name="id15">Incremental parsing</a></li>
<li><a class="reference" href="#event-driven-parsing" id="id16" name="id16">Event-driven parsing</a></li>
</ul>
</li>
<li><a class="reference" href="#namespaces" id="id17" name="id17">Namespaces</a></li>
<li><a class="reference" href="#the-e-factory" id="id18" name="id18">The E-factory</a></li>
<li><a class="reference" href="#elementpath" id="id19" name="id19">ElementPath</a></li>
</ul>
</div>
<p>A common way to import <tt class="docutils literal"><span class="pre">lxml.etree</span></tt> is as follows:</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml import etree
</pre>
<p>If your code only uses the ElementTree API and does not rely on any
functionality that is specific to <tt class="docutils literal"><span class="pre">lxml.etree</span></tt>, you can also use (any part
of) the following import chain as a fall-back to the original ElementTree:</p>
<pre class="literal-block">
try:
  from lxml import etree
  print "running with lxml.etree"
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print "running with cElementTree on Python 2.5+"
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print "running with ElementTree on Python 2.5+"
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print "running with cElementTree"
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print "running with ElementTree"
        except ImportError:
          print "Failed to import ElementTree from any known place"
</pre>
<p>To aid in writing portable code, this tutorial makes it clear in the examples
which part of the presented API is an extension of lxml.etree over the
original <a class="reference" href="http://effbot.org/zone/element-index.htm#documentation">ElementTree API</a>, as defined by Fredrik Lundh's <a class="reference" href="http://effbot.org/zone/element-index.htm">ElementTree
library</a>.</p>
<div class="section">
<h1><a id="the-element-class" name="the-element-class">The Element class</a></h1>
<p>An <tt class="docutils literal"><span class="pre">Element</span></tt> is the main container object for the ElementTree API.  Most of
the XML tree functionality is accessed through this class.  Elements are
easily created through the <tt class="docutils literal"><span class="pre">Element</span></tt> factory:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.Element("root")
</pre>
<p>The XML tag name of elements is accessed through the <tt class="docutils literal"><span class="pre">tag</span></tt> property:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.tag
root
</pre>
<p>Elements are organised in an XML tree structure.  To create child elements and
add them to a parent element, you can use the <tt class="docutils literal"><span class="pre">append()</span></tt> method:</p>
<pre class="literal-block">
&gt;&gt;&gt; root.append( etree.Element("child1") )
</pre>
<p>However, this is so common that there is a shorter and much more efficient way
to do this: the <tt class="docutils literal"><span class="pre">SubElement</span></tt> factory.  It accepts the same arguments as the
<tt class="docutils literal"><span class="pre">Element</span></tt> factory, but additionally requires the parent as first argument:</p>
<pre class="literal-block">
&gt;&gt;&gt; child2 = etree.SubElement(root, "child2")
&gt;&gt;&gt; child3 = etree.SubElement(root, "child3")
</pre>
<p>To see that this is really XML, you can serialise the tree you have created:</p>
<pre class="literal-block">
&gt;&gt;&gt; print etree.tostring(root, pretty_print=True),
&lt;root&gt;
  &lt;child1/&gt;
  &lt;child2/&gt;
  &lt;child3/&gt;
&lt;/root&gt;
</pre>
<div class="section">
<h2><a id="elements-are-lists" name="elements-are-lists">Elements are lists</a></h2>
<p>To make the access to these subelements as easy and straight forward as
possible, elements behave like normal Python lists:</p>
<pre class="literal-block">
&gt;&gt;&gt; child = root[0]
&gt;&gt;&gt; print child.tag
child1

&gt;&gt;&gt; print len(root)
3

&gt;&gt;&gt; root.index(root[1]) # lxml.etree only!
1

&gt;&gt;&gt; children = list(root)

&gt;&gt;&gt; for child in root:
...     print child.tag
child1
child2
child3

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

&gt;&gt;&gt; print start[0].tag
child0
&gt;&gt;&gt; print end[0].tag
child3

&gt;&gt;&gt; root[0] = root[-1] # this moves the element!
&gt;&gt;&gt; for child in root:
...     print child.tag
child3
child1
child2
</pre>
<p>Prior to ElementTree 1.3 and lxml 2.0, you could also check the truth value of
an Element to see if it has children, i.e. if the list of children is empty.
This is no longer supported as people tend to find it surprising that a
non-None reference to an existing Element can evaluate to False.  Instead, use
<tt class="docutils literal"><span class="pre">len(element)</span></tt>, which is both more explicit and less error prone.</p>
<p>Note in the examples that the last element was <em>moved</em> to a different position
in the last example.  This is a difference from the original ElementTree (and
from lists), where elements can sit in multiple positions of any number of
trees.  In lxml.etree, elements can only sit in one position of one tree at a
time.</p>
<p>If you want to <em>copy</em> an element to a different position, consider creating an
independent <em>deep copy</em> using the <tt class="docutils literal"><span class="pre">copy</span></tt> module from Python's standard
library:</p>
<pre class="literal-block">
&gt;&gt;&gt; from copy import deepcopy

&gt;&gt;&gt; element = etree.Element("neu")
&gt;&gt;&gt; element.append( deepcopy(root[1]) )

&gt;&gt;&gt; print element[0].tag
child1
&gt;&gt;&gt; print [ c.tag for c in root ]
['child3', 'child1', 'child2']
</pre>
<p>The way up in the tree is provided through the <tt class="docutils literal"><span class="pre">getparent()</span></tt> method:</p>
<pre class="literal-block">
&gt;&gt;&gt; root is root[0].getparent()  # lxml.etree only!
True
</pre>
<p>The siblings (or neighbours) of an element are accessed as next and previous
elements:</p>
<pre class="literal-block">
&gt;&gt;&gt; root[0] is root[1].getprevious() # lxml.etree only!
True
&gt;&gt;&gt; root[1] is root[0].getnext() # lxml.etree only!
True
</pre>
</div>
<div class="section">
<h2><a id="elements-carry-attributes" name="elements-carry-attributes">Elements carry attributes</a></h2>
<p>XML elements support attributes.  You can create them directly in the Element
factory:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.Element("root", interesting="totally")
&gt;&gt;&gt; print etree.tostring(root)
&lt;root interesting="totally"/&gt;
</pre>
<p>Fast and direct access to these attributes is provided by the <tt class="docutils literal"><span class="pre">set()</span></tt> and
<tt class="docutils literal"><span class="pre">get()</span></tt> methods of elements:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.get("interesting")
totally

&gt;&gt;&gt; root.set("interesting", "somewhat")
&gt;&gt;&gt; print root.get("interesting")
somewhat
</pre>
<p>However, a very convenient way of dealing with them is through the dictionary
interface of the <tt class="docutils literal"><span class="pre">attrib</span></tt> property:</p>
<pre class="literal-block">
&gt;&gt;&gt; attributes = root.attrib

&gt;&gt;&gt; print attributes["interesting"]
somewhat

&gt;&gt;&gt; print attributes.get("hello")
None

&gt;&gt;&gt; attributes["hello"] = "Guten Tag"
&gt;&gt;&gt; print attributes.get("hello")
Guten Tag
&gt;&gt;&gt; print root.get("hello")
Guten Tag
</pre>
</div>
<div class="section">
<h2><a id="elements-contain-text" name="elements-contain-text">Elements contain text</a></h2>
<p>Elements can contain text:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.Element("root")
&gt;&gt;&gt; root.text = "TEXT"

&gt;&gt;&gt; print root.text
TEXT

&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;TEXT&lt;/root&gt;
</pre>
<p>In many XML documents (<em>data-centric</em> documents), this is the only place where
text can be found.  It is encapsulated by a leaf tag at the very bottom of the
tree hierarchy.</p>
<p>However, if XML is used for tagged text documents such as (X)HTML, text can
also appear between different elements, right in the middle of the tree:</p>
<pre class="literal-block">
&lt;html&gt;&lt;body&gt;Hello&lt;br/&gt;World&lt;/body&gt;&lt;/html&gt;
</pre>
<p>Here, the <tt class="docutils literal"><span class="pre">&lt;br/&gt;</span></tt> tag is surrounded by text.  This is often referred to as
<em>document-style</em> or <em>mixed-content</em> XML.  Elements support this through their
<tt class="docutils literal"><span class="pre">tail</span></tt> property.  It contains the text that directly follows the element, up
to the next element in the XML tree:</p>
<pre class="literal-block">
&gt;&gt;&gt; html = etree.Element("html")
&gt;&gt;&gt; body = etree.SubElement(html, "body")
&gt;&gt;&gt; body.text = "TEXT"

&gt;&gt;&gt; print etree.tostring(html)
&lt;html&gt;&lt;body&gt;TEXT&lt;/body&gt;&lt;/html&gt;

&gt;&gt;&gt; br = etree.SubElement(body, "br")
&gt;&gt;&gt; print etree.tostring(html)
&lt;html&gt;&lt;body&gt;TEXT&lt;br/&gt;&lt;/body&gt;&lt;/html&gt;

&gt;&gt;&gt; br.tail = "TAIL"
&gt;&gt;&gt; print etree.tostring(html)
&lt;html&gt;&lt;body&gt;TEXT&lt;br/&gt;TAIL&lt;/body&gt;&lt;/html&gt;
</pre>
<p>The two properties <tt class="docutils literal"><span class="pre">.text</span></tt> and <tt class="docutils literal"><span class="pre">.tail</span></tt> are enough to represent any
text content in an XML document.  This way, the ElementTree API does
not require any <a class="reference" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-1312295772">special text nodes</a> in addition to the Element
class, that tend to get in the way fairly often (as you might know
from classic <a class="reference" href="http://www.w3.org/TR/DOM-Level-3-Core/core.html">DOM</a> APIs).</p>
<p>However, there are cases where the tail text also gets in the way.
For example, when you serialise an Element from within the tree, you
do not always want its tail text in the result (although you would
still want the tail text of its children).  For this purpose, the
<tt class="docutils literal"><span class="pre">tostring()</span></tt> function accepts the keyword argument <tt class="docutils literal"><span class="pre">with_tail</span></tt>:</p>
<pre class="literal-block">
&gt;&gt;&gt; print etree.tostring(br)
&lt;br/&gt;TAIL
&gt;&gt;&gt; print etree.tostring(br, with_tail=False) # lxml.etree only!
&lt;br/&gt;
</pre>
<p>If you want to read <em>only</em> the text, i.e. without any intermediate
tags, you have to recursively concatenate all <tt class="docutils literal"><span class="pre">text</span></tt> and <tt class="docutils literal"><span class="pre">tail</span></tt>
attributes in the correct order.  Again, the <tt class="docutils literal"><span class="pre">tostring()</span></tt> function
comes to the rescue, this time using the <tt class="docutils literal"><span class="pre">method</span></tt> keyword:</p>
<pre class="literal-block">
&gt;&gt;&gt; print etree.tostring(html, method="text")
TEXTTAIL
</pre>
</div>
<div class="section">
<h2><a id="using-xpath-to-find-text" name="using-xpath-to-find-text">Using XPath to find text</a></h2>
<p>Another way to extract the text content of a tree is <a class="reference" href="xpathxslt.html#xpath">XPath</a>, which
also allows you to extract the separate text chunks into a list:</p>
<pre class="literal-block">
&gt;&gt;&gt; print html.xpath("string()") # lxml.etree only!
TEXTTAIL
&gt;&gt;&gt; print html.xpath("//text()") # lxml.etree only!
['TEXT', 'TAIL']
</pre>
<p>If you want to use this more often, you can wrap it in a function:</p>
<pre class="literal-block">
&gt;&gt;&gt; build_text_list = etree.XPath("//text()") # lxml.etree only!
&gt;&gt;&gt; print build_text_list(html)
['TEXT', 'TAIL']
</pre>
<p>Note that a string result returned by XPath is a special 'smart'
object that knows about its origins.  You can ask it where it came
from through its <tt class="docutils literal"><span class="pre">getparent()</span></tt> method, just as you would with
Elements:</p>
<pre class="literal-block">
&gt;&gt;&gt; texts = build_text_list(html)
&gt;&gt;&gt; print texts[0]
TEXT
&gt;&gt;&gt; parent = texts[0].getparent()
&gt;&gt;&gt; print parent.tag
body

&gt;&gt;&gt; print texts[1]
TAIL
&gt;&gt;&gt; print texts[1].getparent().tag
br
</pre>
<p>You can also find out if it's normal text content or tail text:</p>
<pre class="literal-block">
&gt;&gt;&gt; print texts[0].is_text
True
&gt;&gt;&gt; print texts[1].is_text
False
&gt;&gt;&gt; print texts[1].is_tail
True
</pre>
<p>While this works for the results of the <tt class="docutils literal"><span class="pre">text()</span></tt> function, lxml will
not to tell you the origin of a string value that was constructed by
the XPath functions <tt class="docutils literal"><span class="pre">string()</span></tt> or <tt class="docutils literal"><span class="pre">concat()</span></tt>:</p>
<pre class="literal-block">
&gt;&gt;&gt; stringify = etree.XPath("string()")
&gt;&gt;&gt; print stringify(html)
TEXTTAIL
&gt;&gt;&gt; print stringify(html).getparent()
None
</pre>
</div>
<div class="section">
<h2><a id="tree-iteration" name="tree-iteration">Tree iteration</a></h2>
<p>For problems like the above, where you want to recursively traverse the tree
and do something with its elements, tree iteration is a very convenient
solution.  Elements provide a tree iterator for this purpose.  It yields
elements in <em>document order</em>, i.e. in the order their tags would appear if you
serialised the tree to XML:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.Element("root")
&gt;&gt;&gt; etree.SubElement(root, "child").text = "Child 1"
&gt;&gt;&gt; etree.SubElement(root, "child").text = "Child 2"
&gt;&gt;&gt; etree.SubElement(root, "another").text = "Child 3"

&gt;&gt;&gt; print etree.tostring(root, pretty_print=True),
&lt;root&gt;
  &lt;child&gt;Child 1&lt;/child&gt;
  &lt;child&gt;Child 2&lt;/child&gt;
  &lt;another&gt;Child 3&lt;/another&gt;
&lt;/root&gt;

&gt;&gt;&gt; for element in root.iter():
...     print element.tag, '-', element.text
root - None
child - Child 1
child - Child 2
another - Child 3
</pre>
<p>If you know you are only interested in a single tag, you can pass its name to
<tt class="docutils literal"><span class="pre">iter()</span></tt> to have it filter for you:</p>
<pre class="literal-block">
&gt;&gt;&gt; for element in root.iter("child"):
...     print element.tag, '-', element.text
child - Child 1
child - Child 2
</pre>
<p>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
<tt class="docutils literal"><span class="pre">Element</span></tt> factory as tag parameter:</p>
<pre class="literal-block">
&gt;&gt;&gt; root.append(etree.Entity("#234"))
&gt;&gt;&gt; root.append(etree.Comment("some comment"))

&gt;&gt;&gt; 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: &amp;#234; - &amp;#234;
SPECIAL: &lt;!--some comment--&gt; - some comment

&gt;&gt;&gt; for element in root.iter(tag=etree.Element):
...     print element.tag, '-', element.text
root - None
child - Child 1
child - Child 2
another - Child 3

&gt;&gt;&gt; for element in root.iter(tag=etree.Entity):
...     print element.text
&amp;#234;
</pre>
<p>In lxml.etree, elements provide <a class="reference" href="api.html#iteration">further iterators</a> for all directions in the
tree: children, parents (or rather ancestors) and siblings.</p>
</div>
<div class="section">
<h2><a id="serialisation" name="serialisation">Serialisation</a></h2>
<p>Serialisation commonly uses the <tt class="docutils literal"><span class="pre">tostring()</span></tt> function that returns a
string, or the <tt class="docutils literal"><span class="pre">ElementTree.write()</span></tt> method that writes to a file or
file-like object.  Both accept the same keyword arguments like
<tt class="docutils literal"><span class="pre">pretty_print</span></tt> for formatted output or <tt class="docutils literal"><span class="pre">encoding</span></tt> to select a
specific output encoding other than plain ASCII:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML('&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;')

&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;

&gt;&gt;&gt; print etree.tostring(root, xml_declaration=True)
&lt;?xml version='1.0' encoding='ASCII'?&gt;
&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;

&gt;&gt;&gt; print etree.tostring(root, encoding='iso-8859-1')
&lt;?xml version='1.0' encoding='iso-8859-1'?&gt;
&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;

&gt;&gt;&gt; print etree.tostring(root, pretty_print=True),
&lt;root&gt;
  &lt;a&gt;
    &lt;b/&gt;
  &lt;/a&gt;
&lt;/root&gt;
</pre>
<p>Note the newline that is appended at the end when pretty printing the
output.</p>
<p>Since lxml 2.0 (and ElementTree 1.3), the serialisation functions can
do more than XML serialisation.  You can serialise to HTML or extract
the text content by passing the <tt class="docutils literal"><span class="pre">method</span></tt> keyword:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML('&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Hello&lt;br/&gt;World&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;')

&gt;&gt;&gt; print etree.tostring(root) # default: method = 'xml'
&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Hello&lt;br/&gt;World&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;

&gt;&gt;&gt; print etree.tostring(root, method='xml') # same as above
&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Hello&lt;br/&gt;World&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;

&gt;&gt;&gt; print etree.tostring(root, method='html')
&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;p&gt;Hello&lt;br&gt;World&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;

&gt;&gt;&gt; print etree.tostring(root, method='html', pretty_print=True),
&lt;html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;&lt;p&gt;Hello&lt;br&gt;World&lt;/p&gt;&lt;/body&gt;
&lt;/html&gt;

&gt;&gt;&gt; print etree.tostring(root, method='text')
HelloWorld
</pre>
<p>For the plain text output, serialising to a Python unicode string
might become handy.  Just pass the <tt class="docutils literal"><span class="pre">unicode</span></tt> type as encoding:</p>
<pre class="literal-block">
&gt;&gt;&gt; etree.tostring(root, encoding=unicode, method='text')
u'HelloWorld'
</pre>
</div>
</div>
<div class="section">
<h1><a id="the-elementtree-class" name="the-elementtree-class">The ElementTree class</a></h1>
<p>An <tt class="docutils literal"><span class="pre">ElementTree</span></tt> is mainly a document wrapper around a tree with a
root node.  It provides a couple of methods for parsing, serialisation
and general document handling.  One of the bigger differences is that
it serialises as a complete document, as opposed to a single
<tt class="docutils literal"><span class="pre">Element</span></tt>.  This includes top-level processing instructions and
comments, as well as a DOCTYPE and other DTD content in the document:</p>
<pre class="literal-block">
&gt;&gt;&gt; from StringIO import StringIO
&gt;&gt;&gt; tree = etree.parse(StringIO('''\
... &lt;?xml version="1.0"?&gt;
... &lt;!DOCTYPE root SYSTEM "test" [ &lt;!ENTITY tasty "eggs"&gt; ]&gt;
... &lt;root&gt;
...   &lt;a&gt;&amp;tasty;&lt;/a&gt;
... &lt;/root&gt;
... '''))

&gt;&gt;&gt; print tree.docinfo.doctype
&lt;!DOCTYPE root SYSTEM "test"&gt;

&gt;&gt;&gt; # lxml 1.3.4 and later
&gt;&gt;&gt; print etree.tostring(tree)
&lt;!DOCTYPE root SYSTEM "test" [
&lt;!ENTITY tasty "eggs"&gt;
]&gt;
&lt;root&gt;
  &lt;a&gt;eggs&lt;/a&gt;
&lt;/root&gt;

&gt;&gt;&gt; # lxml 1.3.4 and later
&gt;&gt;&gt; print etree.tostring(etree.ElementTree(tree.getroot()))
&lt;!DOCTYPE root SYSTEM "test" [
&lt;!ENTITY tasty "eggs"&gt;
]&gt;
&lt;root&gt;
  &lt;a&gt;eggs&lt;/a&gt;
&lt;/root&gt;

&gt;&gt;&gt; # ElementTree and lxml &lt;= 1.3.3
&gt;&gt;&gt; print etree.tostring(tree.getroot())
&lt;root&gt;
  &lt;a&gt;eggs&lt;/a&gt;
&lt;/root&gt;
</pre>
<p>Note that this has changed in lxml 1.3.4 to match the behaviour of the
upcoming lxml 2.0.  Before, both would serialise without DTD content, which
made lxml loose DTD information in an input-output cycle.</p>
</div>
<div class="section">
<h1><a id="parsing-from-strings-and-files" name="parsing-from-strings-and-files">Parsing from strings and files</a></h1>
<p><tt class="docutils literal"><span class="pre">lxml.etree</span></tt> supports parsing XML in a number of ways and from all
important sources, namely strings, files, URLs (http/ftp) and
file-like objects.  The main parse functions are <tt class="docutils literal"><span class="pre">fromstring()</span></tt> and
<tt class="docutils literal"><span class="pre">parse()</span></tt>, both called with the source as first argument.  By
default, they use the standard parser, but you can always pass a
different parser as second argument.</p>
<div class="section">
<h2><a id="the-fromstring-function" name="the-fromstring-function">The fromstring() function</a></h2>
<p>The <tt class="docutils literal"><span class="pre">fromstring()</span></tt> function is the easiest way to parse a string:</p>
<pre class="literal-block">
&gt;&gt;&gt; some_xml_data = "&lt;root&gt;data&lt;/root&gt;"

&gt;&gt;&gt; root = etree.fromstring(some_xml_data)
&gt;&gt;&gt; print root.tag
root
&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;data&lt;/root&gt;
</pre>
</div>
<div class="section">
<h2><a id="the-xml-function" name="the-xml-function">The XML() function</a></h2>
<p>The <tt class="docutils literal"><span class="pre">XML()</span></tt> function behaves like the <tt class="docutils literal"><span class="pre">fromstring()</span></tt> function, but is
commonly used to write XML literals right into the source:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML("&lt;root&gt;data&lt;/root&gt;")
&gt;&gt;&gt; print root.tag
root
&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;data&lt;/root&gt;
</pre>
</div>
<div class="section">
<h2><a id="the-parse-function" name="the-parse-function">The parse() function</a></h2>
<p>The <tt class="docutils literal"><span class="pre">parse()</span></tt> function is used to parse from files and file-like objects:</p>
<pre class="literal-block">
&gt;&gt;&gt; some_file_like = StringIO("&lt;root&gt;data&lt;/root&gt;")

&gt;&gt;&gt; tree = etree.parse(some_file_like)

&gt;&gt;&gt; print etree.tostring(tree)
&lt;root&gt;data&lt;/root&gt;
</pre>
<p>Note that <tt class="docutils literal"><span class="pre">parse()</span></tt> returns an ElementTree object, not an Element object as
the string parser functions:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = tree.getroot()
&gt;&gt;&gt; print root.tag
root
&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;data&lt;/root&gt;
</pre>
<p>The reasoning behind this difference is that <tt class="docutils literal"><span class="pre">parse()</span></tt> returns a
complete document from a file, while the string parsing functions are
commonly used to parse XML fragments.</p>
<p>The <tt class="docutils literal"><span class="pre">parse()</span></tt> function supports any of the following sources:</p>
<ul class="simple">
<li>an open file object</li>
<li>a file-like object that has a <tt class="docutils literal"><span class="pre">.read(byte_count)</span></tt> method returning
a byte string on each call</li>
<li>a filename string</li>
<li>an HTTP or FTP URL string</li>
</ul>
<p>Note that passing a filename or URL is usually faster than passing an
open file.</p>
</div>
<div class="section">
<h2><a id="parser-objects" name="parser-objects">Parser objects</a></h2>
<p>By default, <tt class="docutils literal"><span class="pre">lxml.etree</span></tt> uses a standard parser with a default setup.  If
you want to configure the parser, you can create a you instance:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser(remove_blank_text=True) # lxml.etree only!
</pre>
<p>This creates a parser that removes empty text between tags while parsing,
which can reduce the size of the tree and avoid dangling tail text if you know
that whitespace-only content is not meaningful for your data.  An example:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML("&lt;root&gt;  &lt;a/&gt;   &lt;b&gt;  &lt;/b&gt;     &lt;/root&gt;", parser)

&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;&lt;a/&gt;&lt;b&gt;  &lt;/b&gt;&lt;/root&gt;
</pre>
<p>Note that the whitespace content inside the <tt class="docutils literal"><span class="pre">&lt;b&gt;</span></tt> tag was not removed, as
content at leaf elements tends to be data content (even if blank).  You can
easily remove it in an additional step by traversing the tree:</p>
<pre class="literal-block">
&gt;&gt;&gt; for element in root.iter("*"):
...     if element.text is not None and not element.text.strip():
...         element.text = None

&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;&lt;a/&gt;&lt;b/&gt;&lt;/root&gt;
</pre>
<p>See <tt class="docutils literal"><span class="pre">help(etree.XMLParser)</span></tt> to find out about the available parser options.</p>
</div>
<div class="section">
<h2><a id="incremental-parsing" name="incremental-parsing">Incremental parsing</a></h2>
<p><tt class="docutils literal"><span class="pre">lxml.etree</span></tt> provides two ways for incremental step-by-step parsing.  One is
through file-like objects, where it calls the <tt class="docutils literal"><span class="pre">read()</span></tt> method repeatedly.
This is best used where the data arrives from a source like <tt class="docutils literal"><span class="pre">urllib</span></tt> or any
other file-like object that can provide data on request.  Note that the parser
will block and wait until data becomes available in this case:</p>
<pre class="literal-block">
&gt;&gt;&gt; class DataSource:
...     data = iter(["&lt;roo", "t&gt;&lt;", "a/", "&gt;&lt;", "/root&gt;"])
...     def read(self, requested_size):
...         try:
...             return self.data.next()
...         except StopIteration:
...             return ""

&gt;&gt;&gt; tree = etree.parse(DataSource())

&gt;&gt;&gt; print etree.tostring(tree)
&lt;root&gt;&lt;a/&gt;&lt;/root&gt;
</pre>
<p>The second way is through a feed parser interface, given by the <tt class="docutils literal"><span class="pre">feed(data)</span></tt>
and <tt class="docutils literal"><span class="pre">close()</span></tt> methods:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser()

&gt;&gt;&gt; parser.feed("&lt;roo")
&gt;&gt;&gt; parser.feed("t&gt;&lt;")
&gt;&gt;&gt; parser.feed("a/")
&gt;&gt;&gt; parser.feed("&gt;&lt;")
&gt;&gt;&gt; parser.feed("/root&gt;")

&gt;&gt;&gt; root = parser.close()

&gt;&gt;&gt; print etree.tostring(root)
&lt;root&gt;&lt;a/&gt;&lt;/root&gt;
</pre>
<p>Here, you can interrupt the parsing process at any time and continue it later
on with another call to the <tt class="docutils literal"><span class="pre">feed()</span></tt> method.  This comes in handy if you
want to avoid blocking calls to the parser, e.g. in frameworks like Twisted,
or whenever data comes in slowly or in chunks and you want to do other things
while waiting for the next chunk.</p>
<p>After calling the <tt class="docutils literal"><span class="pre">close()</span></tt> method (or when an exception was raised
by the parser), you can reuse the parser by calling its <tt class="docutils literal"><span class="pre">feed()</span></tt>
method again:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser.feed("&lt;root/&gt;")
&gt;&gt;&gt; root = parser.close()
&gt;&gt;&gt; print etree.tostring(root)
&lt;root/&gt;
</pre>
</div>
<div class="section">
<h2><a id="event-driven-parsing" name="event-driven-parsing">Event-driven parsing</a></h2>
<p>Sometimes, all you need from a document is a small fraction somewhere deep
inside the tree, so parsing the whole tree into memory, traversing it and
dropping it can be too much overhead.  <tt class="docutils literal"><span class="pre">lxml.etree</span></tt> supports this use case
with two event-driven parser interfaces, one that generates parser events
while building the tree (<tt class="docutils literal"><span class="pre">iterparse</span></tt>), and one that does not build the tree
at all, and instead calls feedback methods on a target object in a SAX-like
fashion.</p>
<p>Here is a simple <tt class="docutils literal"><span class="pre">iterparse()</span></tt> example:</p>
<pre class="literal-block">
&gt;&gt;&gt; some_file_like = StringIO("&lt;root&gt;&lt;a&gt;data&lt;/a&gt;&lt;/root&gt;")

&gt;&gt;&gt; for event, element in etree.iterparse(some_file_like):
...     print "%s, %4s, %s" % (event, element.tag, element.text)
end,    a, data
end, root, None
</pre>
<p>By default, <tt class="docutils literal"><span class="pre">iterparse()</span></tt> only generates events when it is done parsing an
element, but you can control this through the <tt class="docutils literal"><span class="pre">events</span></tt> keyword argument:</p>
<pre class="literal-block">
&gt;&gt;&gt; some_file_like = StringIO("&lt;root&gt;&lt;a&gt;data&lt;/a&gt;&lt;/root&gt;")

&gt;&gt;&gt; for event, element in etree.iterparse(some_file_like,
...                                       events=("start", "end")):
...     print "%5s, %4s, %s" % (event, element.tag, element.text)
start, root, None
start,    a, data
  end,    a, data
  end, root, None
</pre>
<p>Note that the text, tail and children of an Element are not necessarily there
yet when receiving the <tt class="docutils literal"><span class="pre">start</span></tt> event.  Only the <tt class="docutils literal"><span class="pre">end</span></tt> event guarantees
that the Element has been parsed completely.</p>
<p>It also allows to <tt class="docutils literal"><span class="pre">.clear()</span></tt> or modify the content of an Element to
save memory. So if you parse a large tree and you want to keep memory
usage small, you should clean up parts of the tree that you no longer
need:</p>
<pre class="literal-block">
&gt;&gt;&gt; some_file_like = StringIO(
...     "&lt;root&gt;&lt;a&gt;&lt;b&gt;data&lt;/b&gt;&lt;/a&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;")

&gt;&gt;&gt; for event, element in etree.iterparse(some_file_like):
...     if element.tag == 'b':
...         print element.text
...     elif element.tag == 'a':
...         print "** cleaning up the subtree"
...         element.clear()
data
** cleaning up the subtree
None
** cleaning up the subtree
</pre>
<p>If memory is a real bottleneck, or if building the tree is not desired at all,
the target parser interface of <tt class="docutils literal"><span class="pre">lxml.etree</span></tt> can be used.  It creates
SAX-like events by calling the methods of a target object.  By implementing
some or all of these methods, you can control which events are generated:</p>
<pre class="literal-block">
&gt;&gt;&gt; class ParserTarget:
...     events = []
...     def start(self, tag, attrib):
...         self.events.append(("start", tag, attrib))
...     def close(self):
...         return self.events

&gt;&gt;&gt; parser = etree.XMLParser(target=ParserTarget())
&gt;&gt;&gt; events = etree.fromstring('&lt;root test="true"/&gt;', parser)

&gt;&gt;&gt; for event in events:
...     print 'event: %s - tag: %s' % (event[0], event[1])
...     for attr, value in event[2].iteritems():
...         print ' * %s = %s' % (attr, value)
event: start - tag: root
 * test = true
</pre>
</div>
</div>
<div class="section">
<h1><a id="namespaces" name="namespaces">Namespaces</a></h1>
<p>The ElementTree API avoids <a class="reference" href="http://www.w3.org/TR/xml-names/#ns-qualnames">namespace prefixes</a> wherever possible and deploys
the real namespaces instead:</p>
<pre class="literal-block">
&gt;&gt;&gt; xhtml = etree.Element("{http://www.w3.org/1999/xhtml}html")
&gt;&gt;&gt; body = etree.SubElement(xhtml, "{http://www.w3.org/1999/xhtml}body")
&gt;&gt;&gt; body.text = "Hello World"

&gt;&gt;&gt; print etree.tostring(xhtml, pretty_print=True),
&lt;html:html xmlns:html="http://www.w3.org/1999/xhtml"&gt;
  &lt;html:body&gt;Hello World&lt;/html:body&gt;
&lt;/html:html&gt;
</pre>
<p>As you can see, prefixes only become important when you serialise the result.
However, the above code becomes somewhat verbose due to the lengthy namespace
names.  And retyping or copying a string over and over again is error prone.
It is therefore common practice to store a namespace URI in a global variable.
To adapt the namespace prefixes for serialisation, you can also pass a mapping
to the Element factory, e.g. to define the default namespace:</p>
<pre class="literal-block">
&gt;&gt;&gt; XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"
&gt;&gt;&gt; XHTML = "{%s}" % XHTML_NAMESPACE

&gt;&gt;&gt; NSMAP = {None : XHTML_NAMESPACE} # the default namespace (no prefix)

&gt;&gt;&gt; xhtml = etree.Element(XHTML + "html", nsmap=NSMAP) # lxml only!
&gt;&gt;&gt; body = etree.SubElement(xhtml, XHTML + "body")
&gt;&gt;&gt; body.text = "Hello World"

&gt;&gt;&gt; print etree.tostring(xhtml, pretty_print=True),
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;body&gt;Hello World&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Namespaces on attributes work alike:</p>
<pre class="literal-block">
&gt;&gt;&gt; body.set(XHTML + "bgcolor", "#CCFFAA")

&gt;&gt;&gt; print etree.tostring(xhtml, pretty_print=True),
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;body bgcolor="#CCFFAA"&gt;Hello World&lt;/body&gt;
&lt;/html&gt;

&gt;&gt;&gt; print body.get("bgcolor")
None
&gt;&gt;&gt; body.get(XHTML + "bgcolor")
'#CCFFAA'
</pre>
<p>You can also use XPath in this way:</p>
<pre class="literal-block">
&gt;&gt;&gt; find_xhtml_body = etree.ETXPath(      # lxml only !
...     "//{%s}body" % XHTML_NAMESPACE)
&gt;&gt;&gt; results = find_xhtml_body(xhtml)

&gt;&gt;&gt; print results[0].tag
{http://www.w3.org/1999/xhtml}body
</pre>
</div>
<div class="section">
<h1><a id="the-e-factory" name="the-e-factory">The E-factory</a></h1>
<p>The <tt class="docutils literal"><span class="pre">E-factory</span></tt> provides a simple and compact syntax for generating XML and
HTML:</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml.builder import E

&gt;&gt;&gt; def CLASS(*args): # class is a reserved word in Python
...     return {"class":' '.join(args)}

&gt;&gt;&gt; html = page = (
...   E.html(       # create an Element called "html"
...     E.head(
...       E.title("This is a sample document")
...     ),
...     E.body(
...       E.h1("Hello!", CLASS("title")),
...       E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
...       E.p("This is another paragraph, with a", "\n      ",
...         E.a("link", href="http://www.python.org"), "."),
...       E.p("Here are some reservered characters: &lt;spam&amp;egg&gt;."),
...       etree.XML("&lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;"),
...     )
...   )
... )

&gt;&gt;&gt; print etree.tostring(page, pretty_print=True),
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;This is a sample document&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1 class="title"&gt;Hello!&lt;/h1&gt;
    &lt;p&gt;This is a paragraph with &lt;b&gt;bold&lt;/b&gt; text in it!&lt;/p&gt;
    &lt;p&gt;This is another paragraph, with a
      &lt;a href="http://www.python.org"&gt;link&lt;/a&gt;.&lt;/p&gt;
    &lt;p&gt;Here are some reservered characters: &amp;lt;spam&amp;amp;egg&amp;gt;.&lt;/p&gt;
    &lt;p&gt;And finally an embedded XHTML fragment.&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The Element creation based on attribute access makes it easy to build up a
simple vocabulary for an XML language:</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml.builder import ElementMaker # lxml only !

&gt;&gt;&gt; E = ElementMaker(namespace="http://my.de/fault/namespace",
...                  nsmap={'p' : "http://my.de/fault/namespace"})

&gt;&gt;&gt; DOC = E.doc
&gt;&gt;&gt; TITLE = E.title
&gt;&gt;&gt; SECTION = E.section
&gt;&gt;&gt; PAR = E.par

&gt;&gt;&gt; my_doc = DOC(
...   TITLE("The dog and the hog"),
...   SECTION(
...     TITLE("The dog"),
...     PAR("Once upon a time, ..."),
...     PAR("And then ...")
...   ),
...   SECTION(
...     TITLE("The hog"),
...     PAR("Sooner or later ...")
...   )
... )

&gt;&gt;&gt; print etree.tostring(my_doc, pretty_print=True),
&lt;p:doc xmlns:p="http://my.de/fault/namespace"&gt;
  &lt;p:title&gt;The dog and the hog&lt;/p:title&gt;
  &lt;p:section&gt;
    &lt;p:title&gt;The dog&lt;/p:title&gt;
    &lt;p:par&gt;Once upon a time, ...&lt;/p:par&gt;
    &lt;p:par&gt;And then ...&lt;/p:par&gt;
  &lt;/p:section&gt;
  &lt;p:section&gt;
    &lt;p:title&gt;The hog&lt;/p:title&gt;
    &lt;p:par&gt;Sooner or later ...&lt;/p:par&gt;
  &lt;/p:section&gt;
&lt;/p:doc&gt;
</pre>
<p>One such example is the module <tt class="docutils literal"><span class="pre">lxml.html.builder</span></tt>, which provides a
vocabulary for HTML.</p>
</div>
<div class="section">
<h1><a id="elementpath" name="elementpath">ElementPath</a></h1>
<p>The ElementTree library comes with a simple XPath-like path language
called <a class="reference" href="http://effbot.org/zone/element-xpath.htm">ElementPath</a>.  The main difference is that you can use the
<tt class="docutils literal"><span class="pre">{namespace}tag</span></tt> notation in ElementPath expressions.  However,
advanced features like value comparison and functions are not
available.</p>
<p>In addition to a <a class="reference" href="xpathxslt.html#xpath">full XPath implementation</a>, lxml.etree supports the
ElementPath language in the same way ElementTree does, even using
(almost) the same implementation.  The API provides four methods here
that you can find on Elements and ElementTrees:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">iterfind()</span></tt> iterates over all Elements that match the path
expression</li>
<li><tt class="docutils literal"><span class="pre">findall()</span></tt> returns a list of matching Elements</li>
<li><tt class="docutils literal"><span class="pre">find()</span></tt> efficiently returns only the first match</li>
<li><tt class="docutils literal"><span class="pre">findtext()</span></tt> returns the <tt class="docutils literal"><span class="pre">.text</span></tt> content of the first match</li>
</ul>
<p>Here are some examples:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML("&lt;root&gt;&lt;a x='123'&gt;aText&lt;b/&gt;&lt;c/&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;")
</pre>
<p>Find a child of an Element:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.find("b")
None
&gt;&gt;&gt; print root.find("a").tag
a
</pre>
<p>Find an Element anywhere in the tree:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.find(".//b").tag
b
&gt;&gt;&gt; [ b.tag for b in root.iterfind(".//b") ]
['b', 'b']
</pre>
<p>Find Elements with a certain attribute:</p>
<pre class="literal-block">
&gt;&gt;&gt; print root.findall(".//a[@x]")[0].tag
a
&gt;&gt;&gt; print root.findall(".//a[@y]")
[]
</pre>
</div>
</div>
<div class="footer">
<hr class="footer" />
Generated on: 2008-12-12.

</div>
</body>
</html>