Sophie

Sophie

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

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>Parsing XML and HTML with lxml</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div class="document" id="parsing-xml-and-html-with-lxml">
<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 foreign" 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 current" 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">Parsing XML and HTML with lxml</h1>
<p>lxml provides a very simple and powerful API for parsing XML and HTML.  It
supports one-step parsing as well as step-by-step parsing using an
event-driven API (currently only for XML).</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="#parsers" id="id1" name="id1">Parsers</a><ul>
<li><a class="reference" href="#parser-options" id="id2" name="id2">Parser options</a></li>
<li><a class="reference" href="#error-log" id="id3" name="id3">Error log</a></li>
<li><a class="reference" href="#parsing-html" id="id4" name="id4">Parsing HTML</a></li>
<li><a class="reference" href="#doctype-information" id="id5" name="id5">Doctype information</a></li>
</ul>
</li>
<li><a class="reference" href="#the-target-parser-interface" id="id6" name="id6">The target parser interface</a></li>
<li><a class="reference" href="#the-feed-parser-interface" id="id7" name="id7">The feed parser interface</a></li>
<li><a class="reference" href="#iterparse-and-iterwalk" id="id8" name="id8">iterparse and iterwalk</a><ul>
<li><a class="reference" href="#selective-tag-events" id="id9" name="id9">Selective tag events</a></li>
<li><a class="reference" href="#modifying-the-tree" id="id10" name="id10">Modifying the tree</a></li>
<li><a class="reference" href="#iterwalk" id="id11" name="id11">iterwalk</a></li>
</ul>
</li>
<li><a class="reference" href="#python-unicode-strings" id="id12" name="id12">Python unicode strings</a><ul>
<li><a class="reference" href="#serialising-to-unicode-strings" id="id13" name="id13">Serialising to Unicode strings</a></li>
</ul>
</li>
</ul>
</div>
<p>The usual setup procedure:</p>
<pre class="literal-block">
&gt;&gt;&gt; from lxml import etree
&gt;&gt;&gt; from StringIO import StringIO
</pre>
<div class="section">
<h1><a id="parsers" name="parsers">Parsers</a></h1>
<p>Parsers are represented by parser objects.  There is support for parsing both
XML and (broken) HTML.  Note that XHTML is best parsed as XML, parsing it with
the HTML parser can lead to unexpected results.  Here is a simple example for
parsing XML from an in-memory string:</p>
<pre class="literal-block">
&gt;&gt;&gt; xml = '&lt;a xmlns="test"&gt;&lt;b xmlns="test"/&gt;&lt;/a&gt;'

&gt;&gt;&gt; root = etree.fromstring(xml)
&gt;&gt;&gt; print etree.tostring(root)
&lt;a xmlns="test"&gt;&lt;b xmlns="test"/&gt;&lt;/a&gt;
</pre>
<p>To read from a file or file-like object, you can use the <tt class="docutils literal"><span class="pre">parse()</span></tt> function,
which returns an <tt class="docutils literal"><span class="pre">ElementTree</span></tt> object:</p>
<pre class="literal-block">
&gt;&gt;&gt; tree = etree.parse(StringIO(xml))
&gt;&gt;&gt; print etree.tostring(tree.getroot())
&lt;a xmlns="test"&gt;&lt;b xmlns="test"/&gt;&lt;/a&gt;
</pre>
<p>Note how the <tt class="docutils literal"><span class="pre">parse()</span></tt> function reads from a file-like object here.  If
parsing is done from a real file, it is more common (and also somewhat more
efficient) to pass a filename:</p>
<pre class="literal-block">
&gt;&gt;&gt; tree = etree.parse("doc/test.xml")
</pre>
<p>lxml can parse from a local file, an HTTP URL or an FTP URL.  It also
auto-detects and reads gzip-compressed XML files (.gz).</p>
<p>If you want to parse from memory and still provide a base URL for the document
(e.g. to support relative paths in an XInclude), you can pass the <tt class="docutils literal"><span class="pre">base_url</span></tt>
keyword argument:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.fromstring(xml, base_url="http://where.it/is/from.xml")
</pre>
<div class="section">
<h2><a id="parser-options" name="parser-options">Parser options</a></h2>
<p>The parsers accept a number of setup options as keyword arguments.  The above
example is easily extended to clean up namespaces during parsing:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser(ns_clean=True)
&gt;&gt;&gt; tree   = etree.parse(StringIO(xml), parser)
&gt;&gt;&gt; print etree.tostring(tree.getroot())
&lt;a xmlns="test"&gt;&lt;b/&gt;&lt;/a&gt;
</pre>
<p>The keyword arguments in the constructor are mainly based on the libxml2
parser configuration.  A DTD will also be loaded if validation or attribute
default values are requested.</p>
<p>Available boolean keyword arguments:</p>
<ul class="simple">
<li>attribute_defaults - read the DTD (if referenced by the document) and add
the default attributes from it</li>
<li>dtd_validation - validate while parsing (if a DTD was referenced)</li>
<li>load_dtd - load and parse the DTD while parsing (no validation is performed)</li>
<li>no_network - prevent network access when looking up external documents</li>
<li>ns_clean - try to clean up redundant namespace declarations</li>
<li>recover - try hard to parse through broken XML</li>
<li>remove_blank_text - discard blank text nodes between tags</li>
<li>remove_comments - discard comments</li>
<li>compact - use compact storage for short text content (on by default)</li>
</ul>
</div>
<div class="section">
<h2><a id="error-log" name="error-log">Error log</a></h2>
<p>Parsers have an <tt class="docutils literal"><span class="pre">error_log</span></tt> property that lists the errors of the
last parser run:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser()
&gt;&gt;&gt; print len(parser.error_log)
0

&gt;&gt;&gt; tree = etree.XML("&lt;root&gt;&lt;/b&gt;", parser)
Traceback (most recent call last):
  ...
XMLSyntaxError: Opening and ending tag mismatch: root line 1 and b, line 1, column 11

&gt;&gt;&gt; print len(parser.error_log)
1

&gt;&gt;&gt; error = parser.error_log[0]
&gt;&gt;&gt; print error.message
Opening and ending tag mismatch: root line 1 and b
&gt;&gt;&gt; print error.line, error.column
1 11
</pre>
</div>
<div class="section">
<h2><a id="parsing-html" name="parsing-html">Parsing HTML</a></h2>
<p>HTML parsing is similarly simple.  The parsers have a <tt class="docutils literal"><span class="pre">recover</span></tt> keyword
argument that the HTMLParser sets by default.  It lets libxml2 try its best to
return something usable without raising an exception.  You should use libxml2
version 2.6.21 or newer to take advantage of this feature:</p>
<pre class="literal-block">
&gt;&gt;&gt; broken_html = "&lt;html&gt;&lt;head&gt;&lt;title&gt;test&lt;body&gt;&lt;h1&gt;page title&lt;/h3&gt;"

&gt;&gt;&gt; parser = etree.HTMLParser()
&gt;&gt;&gt; tree   = etree.parse(StringIO(broken_html), parser)

&gt;&gt;&gt; print etree.tostring(tree.getroot(), pretty_print=True),
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;test&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;page title&lt;/h1&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Lxml has an HTML function, similar to the XML shortcut known from
ElementTree:</p>
<pre class="literal-block">
&gt;&gt;&gt; html = etree.HTML(broken_html)
&gt;&gt;&gt; print etree.tostring(html, pretty_print=True),
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;test&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;page title&lt;/h1&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The support for parsing broken HTML depends entirely on libxml2's recovery
algorithm.  It is <em>not</em> the fault of lxml if you find documents that are so
heavily broken that the parser cannot handle them.  There is also no guarantee
that the resulting tree will contain all data from the original document.  The
parser may have to drop seriously broken parts when struggling to keep
parsing.  Especially misplaced meta tags can suffer from this, which may lead
to encoding problems.</p>
</div>
<div class="section">
<h2><a id="doctype-information" name="doctype-information">Doctype information</a></h2>
<p>The use of the libxml2 parsers makes some additional information available at
the API level.  Currently, ElementTree objects can access the DOCTYPE
information provided by a parsed document, as well as the XML version and the
original encoding:</p>
<pre class="literal-block">
&gt;&gt;&gt; pub_id  = "-//W3C//DTD XHTML 1.0 Transitional//EN"
&gt;&gt;&gt; sys_url = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
&gt;&gt;&gt; doctype_string = '&lt;!DOCTYPE html PUBLIC "%s" "%s"&gt;' % (pub_id, sys_url)
&gt;&gt;&gt; xml_header = '&lt;?xml version="1.0" encoding="ascii"?&gt;'
&gt;&gt;&gt; xhtml = xml_header + doctype_string + '&lt;html&gt;&lt;body&gt;&lt;/body&gt;&lt;/html&gt;'

&gt;&gt;&gt; tree = etree.parse(StringIO(xhtml))
&gt;&gt;&gt; docinfo = tree.docinfo
&gt;&gt;&gt; print docinfo.public_id
-//W3C//DTD XHTML 1.0 Transitional//EN
&gt;&gt;&gt; print docinfo.system_url
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
&gt;&gt;&gt; docinfo.doctype == doctype_string
True

&gt;&gt;&gt; print docinfo.xml_version
1.0
&gt;&gt;&gt; print docinfo.encoding
ascii
</pre>
</div>
</div>
<div class="section">
<h1><a id="the-target-parser-interface" name="the-target-parser-interface">The target parser interface</a></h1>
<p><a class="reference" href="http://effbot.org/elementtree/elementtree-xmlparser.htm">As in ElementTree</a>, and similar to a SAX event handler, you can pass
a target object to the parser:</p>
<pre class="literal-block">
&gt;&gt;&gt; class EchoTarget:
...     def start(self, tag, attrib):
...         print "start", tag, attrib
...     def end(self, tag):
...         print "end", tag
...     def data(self, data):
...         print "data", repr(data)
...     def close(self):
...         print "close"
...         return "closed!"

&gt;&gt;&gt; parser = etree.XMLParser(target = EchoTarget())

&gt;&gt;&gt; result = etree.XML("&lt;element&gt;some text&lt;/element&gt;", parser)
start element {}
data u'some text'
end element
close

&gt;&gt;&gt; print result
closed!
</pre>
<p>Note that the parser does <em>not</em> build a tree in this case.  The result
of the parser run is what the target object returns from its
<tt class="docutils literal"><span class="pre">close()</span></tt> method.  If you want to return an XML tree here, you have
to create it programmatically in the target object.</p>
</div>
<div class="section">
<h1><a id="the-feed-parser-interface" name="the-feed-parser-interface">The feed parser interface</a></h1>
<p>Since lxml 2.0, the parsers have a feed parser interface that is compatible to
the <a class="reference" href="http://effbot.org/elementtree/elementtree-xmlparser.htm">ElementTree parsers</a>.  You can use it to feed data into the parser in a
controlled step-by-step way.  Note that you can only use one interface at a
time with each parser: the <tt class="docutils literal"><span class="pre">parse()</span></tt> or <tt class="docutils literal"><span class="pre">XML()</span></tt> functions, or the feed
parser interface.</p>
<p>To start parsing with a feed parser, just call its <tt class="docutils literal"><span class="pre">feed()</span></tt> method:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser()

&gt;&gt;&gt; for data in ('&lt;?xml versio', 'n="1.0"?', '&gt;&lt;roo', 't&gt;&lt;a', '/&gt;&lt;/root&gt;'):
...     parser.feed(data)
</pre>
<p>When you are done parsing, you <strong>must</strong> call the <tt class="docutils literal"><span class="pre">close()</span></tt> method to
retrieve the root Element of the parse result document, and to unlock the
parser:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = parser.close()

&gt;&gt;&gt; print root.tag
root
&gt;&gt;&gt; print root[0].tag
a
</pre>
<p>If you do not call <tt class="docutils literal"><span class="pre">close()</span></tt>, the parser will stay locked and subsequent
usages will block till the end of times.  So make sure you also close it in
the exception case.</p>
<p>Another way of achieving the same step-by-step parsing is by writing your own
file-like object that returns a chunk of data on each <tt class="docutils literal"><span class="pre">read()</span></tt> call.  Where
the feed parser interface allows you to actively pass data chunks into the
parser, a file-like object passively responds to <tt class="docutils literal"><span class="pre">read()</span></tt> requests of the
parser itself.  Depending on the data source, either way may be more natural.</p>
<p>Note that the feed parser has its own error log called
<tt class="docutils literal"><span class="pre">feed_error_log</span></tt>.  Errors in the feed parser do not show up in the
normal <tt class="docutils literal"><span class="pre">error_log</span></tt> and vice versa.</p>
<p>You can also combine the feed parser interface with the target parser:</p>
<pre class="literal-block">
&gt;&gt;&gt; parser = etree.XMLParser(target = EchoTarget())

&gt;&gt;&gt; parser.feed("&lt;eleme")
&gt;&gt;&gt; parser.feed("nt&gt;some text&lt;/elem")
start element {}
data u'some text'
&gt;&gt;&gt; parser.feed("ent&gt;")
end element

&gt;&gt;&gt; result = parser.close()
close
&gt;&gt;&gt; print result
closed!
</pre>
<p>Again, this prevents the automatic creating of an XML tree and leaves
all the event handling to the target object.  The <tt class="docutils literal"><span class="pre">close()</span></tt> method
of the parser forwards the return value of the target's <tt class="docutils literal"><span class="pre">close()</span></tt>
method.</p>
</div>
<div class="section">
<h1><a id="iterparse-and-iterwalk" name="iterparse-and-iterwalk">iterparse and iterwalk</a></h1>
<p>As known from ElementTree, the <tt class="docutils literal"><span class="pre">iterparse()</span></tt> utility function returns an
iterator that generates parser events for an XML file (or file-like object),
while building the tree.  The values are tuples <tt class="docutils literal"><span class="pre">(event-type,</span> <span class="pre">object)</span></tt>.  The
event types are 'start', 'end', 'start-ns' and 'end-ns'.</p>
<p>The 'start' and 'end' events represent opening and closing elements and are
accompanied by the respective element.  By default, only 'end' events are
generated:</p>
<pre class="literal-block">
&gt;&gt;&gt; xml = '''\
... &lt;root&gt;
...   &lt;element key='value'&gt;text&lt;/element&gt;
...   &lt;element&gt;text&lt;/element&gt;tail
...   &lt;empty-element xmlns="testns" /&gt;
... &lt;/root&gt;
... '''

&gt;&gt;&gt; context = etree.iterparse(StringIO(xml))
&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
end element
end element
end {testns}empty-element
end root
</pre>
<p>The resulting tree is available through the <tt class="docutils literal"><span class="pre">root</span></tt> property of the iterator:</p>
<pre class="literal-block">
&gt;&gt;&gt; context.root.tag
'root'
</pre>
<p>The other event types can be activated with the <tt class="docutils literal"><span class="pre">events</span></tt> keyword argument:</p>
<pre class="literal-block">
&gt;&gt;&gt; events = ("start", "end")
&gt;&gt;&gt; context = etree.iterparse(StringIO(xml), events=events)
&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
start root
start element
end element
start element
end element
start {testns}empty-element
end {testns}empty-element
end root
</pre>
<div class="section">
<h2><a id="selective-tag-events" name="selective-tag-events">Selective tag events</a></h2>
<p>As an extension over ElementTree, lxml.etree accepts a <tt class="docutils literal"><span class="pre">tag</span></tt> keyword
argument just like <tt class="docutils literal"><span class="pre">element.iter(tag)</span></tt>.  This restricts events to a
specific tag or namespace:</p>
<pre class="literal-block">
&gt;&gt;&gt; context = etree.iterparse(StringIO(xml), tag="element")
&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
end element
end element

&gt;&gt;&gt; events = ("start", "end")
&gt;&gt;&gt; context = etree.iterparse(
...             StringIO(xml), events=events, tag="{testns}*")
&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
start {testns}empty-element
end {testns}empty-element
</pre>
</div>
<div class="section">
<h2><a id="modifying-the-tree" name="modifying-the-tree">Modifying the tree</a></h2>
<p>You can modify the element and its descendants when handling the 'end' event.
To save memory, for example, you can remove subtrees that are no longer
needed:</p>
<pre class="literal-block">
&gt;&gt;&gt; context = etree.iterparse(StringIO(xml))
&gt;&gt;&gt; for action, elem in context:
...     print len(elem),
...     elem.clear()
0 0 0 3
&gt;&gt;&gt; context.root.getchildren()
[]
</pre>
<p><strong>WARNING</strong>: During the 'start' event, the descendants and following siblings
are not yet available and should not be accessed.  During the 'end' event, the
element and its descendants can be freely modified, but its following siblings
should not be accessed.  During either of the two events, you <strong>must not</strong>
modify or move the ancestors (parents) of the current element.  You should
also avoid moving or discarding the element itself.  The golden rule is: do
not touch anything that will have to be touched again by the parser later on.</p>
<p>If you have elements with a long list of children in your XML file and want to
save more memory during parsing, you can clean up the preceding siblings of
the current element:</p>
<pre class="literal-block">
&gt;&gt;&gt; for event, element in etree.iterparse(StringIO(xml)):
...     # ... do something with the element
...     element.clear()                 # clean up children
...     while element.getprevious() is not None:
...         del element.getparent()[0]  # clean up preceding siblings
</pre>
<p>The <tt class="docutils literal"><span class="pre">while</span></tt> loop deletes multiple siblings in a row.  This is only necessary
if you skipped over some of them using the <tt class="docutils literal"><span class="pre">tag</span></tt> keyword argument.
Otherwise, a simple <tt class="docutils literal"><span class="pre">if</span></tt> should do.  The more selective your tag is,
however, the more thought you will have to put into finding the right way to
clean up the elements that were skipped.  Therefore, it is sometimes easier to
traverse all elements and do the tag selection by hand in the event handler
code.</p>
<p>The 'start-ns' and 'end-ns' events notify about namespace declarations and
generate tuples <tt class="docutils literal"><span class="pre">(prefix,</span> <span class="pre">URI)</span></tt>:</p>
<pre class="literal-block">
&gt;&gt;&gt; events = ("start-ns", "end-ns")
&gt;&gt;&gt; context = etree.iterparse(StringIO(xml), events=events)
&gt;&gt;&gt; for action, obj in context:
...     print action, obj
start-ns ('', 'testns')
end-ns None
</pre>
<p>It is common practice to use a list as namespace stack and pop the last entry
on the 'end-ns' event.</p>
</div>
<div class="section">
<h2><a id="iterwalk" name="iterwalk">iterwalk</a></h2>
<p>A second extension over ElementTree is the <tt class="docutils literal"><span class="pre">iterwalk()</span></tt> function.  It
behaves exactly like <tt class="docutils literal"><span class="pre">iterparse()</span></tt>, but works on Elements and ElementTrees:</p>
<pre class="literal-block">
&gt;&gt;&gt; root = etree.XML(xml)
&gt;&gt;&gt; context = etree.iterwalk(
...             root, events=("start", "end"), tag="element")
&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
start element
end element
start element
end element

&gt;&gt;&gt; f = StringIO(xml)
&gt;&gt;&gt; context = etree.iterparse(
...             f, events=("start", "end"), tag="element")

&gt;&gt;&gt; for action, elem in context:
...     print action, elem.tag
start element
end element
start element
end element
</pre>
</div>
</div>
<div class="section">
<h1><a id="python-unicode-strings" name="python-unicode-strings">Python unicode strings</a></h1>
<p>lxml.etree has broader support for Python unicode strings than the ElementTree
library.  First of all, where ElementTree would raise an exception, the
parsers in lxml.etree can handle unicode strings straight away.  This is most
helpful for XML snippets embedded in source code using the <tt class="docutils literal"><span class="pre">XML()</span></tt>
function:</p>
<pre class="literal-block">
&gt;&gt;&gt; uxml = u'&lt;test&gt; \uf8d1 + \uf8d2 &lt;/test&gt;'
&gt;&gt;&gt; uxml
u'&lt;test&gt; \uf8d1 + \uf8d2 &lt;/test&gt;'
&gt;&gt;&gt; root = etree.XML(uxml)
</pre>
<p>This requires, however, that unicode strings do not specify a conflicting
encoding themselves and thus lie about their real encoding:</p>
<pre class="literal-block">
&gt;&gt;&gt; etree.XML(u'&lt;?xml version="1.0" encoding="ASCII"?&gt;\n' + uxml)
Traceback (most recent call last):
  ...
ValueError: Unicode strings with encoding declaration are not supported.
</pre>
<p>Similarly, you will get errors when you try the same with HTML data in a
unicode string that specifies a charset in a meta tag of the header.  You
should generally avoid converting XML/HTML data to unicode before passing it
into the parsers.  It is both slower and error prone.</p>
<div class="section">
<h2><a id="serialising-to-unicode-strings" name="serialising-to-unicode-strings">Serialising to Unicode strings</a></h2>
<p>To serialize the result, you would normally use the <tt class="docutils literal"><span class="pre">tostring()</span></tt>
module function, which serializes to plain ASCII by default or a
number of other byte encodings if asked for:</p>
<pre class="literal-block">
&gt;&gt;&gt; etree.tostring(root)
'&lt;test&gt; &amp;#63697; + &amp;#63698; &lt;/test&gt;'

&gt;&gt;&gt; etree.tostring(root, encoding='UTF-8', xml_declaration=False)
'&lt;test&gt; \xef\xa3\x91 + \xef\xa3\x92 &lt;/test&gt;'
</pre>
<p>As an extension, lxml.etree recognises the unicode type as encoding to
build a Python unicode representation of a tree:</p>
<pre class="literal-block">
&gt;&gt;&gt; etree.tostring(root, encoding=unicode)
u'&lt;test&gt; \uf8d1 + \uf8d2 &lt;/test&gt;'

&gt;&gt;&gt; el = etree.Element("test")
&gt;&gt;&gt; etree.tostring(el, encoding=unicode)
u'&lt;test/&gt;'

&gt;&gt;&gt; subel = etree.SubElement(el, "subtest")
&gt;&gt;&gt; etree.tostring(el, encoding=unicode)
u'&lt;test&gt;&lt;subtest/&gt;&lt;/test&gt;'

&gt;&gt;&gt; tree = etree.ElementTree(el)
&gt;&gt;&gt; etree.tostring(tree, encoding=unicode)
u'&lt;test&gt;&lt;subtest/&gt;&lt;/test&gt;'
</pre>
<p>The result of <tt class="docutils literal"><span class="pre">tostring(encoding=unicode)</span></tt> can be treated like any
other Python unicode string and then passed back into the parsers.
However, if you want to save the result to a file or pass it over the
network, you should use <tt class="docutils literal"><span class="pre">write()</span></tt> or <tt class="docutils literal"><span class="pre">tostring()</span></tt> with a byte
encoding (typically UTF-8) to serialize the XML.  The main reason is
that unicode strings returned by <tt class="docutils literal"><span class="pre">tostring(encoding=unicode)</span></tt> are
not byte streams and they never have an XML declaration to specify
their encoding.  These strings are most likely not parsable by other
XML libraries.</p>
<p>For normal byte encodings, the <tt class="docutils literal"><span class="pre">tostring()</span></tt> function automatically
adds a declaration as needed that reflects the encoding of the
returned string.  This makes it possible for other parsers to
correctly parse the XML byte stream.  Note that using <tt class="docutils literal"><span class="pre">tostring()</span></tt>
with UTF-8 is also considerably faster in most cases.</p>
</div>
</div>
</div>
<div class="footer">
<hr class="footer" />
Generated on: 2008-12-12.

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