How to use Xpath in Python?
<p>What is the library? Is there a full implementation? How is the library used? Where is its website?</p>

<p><a href="http://xmlsoft.org/python.html">libxml2</a> has a number of advantages:</p>

<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a></li>
<li>Active development and a community participation </li>
<li>Speed. This is really a python wrapper around a C implementation. </li>
<li>Ubiquity. The libxml2 library is pervasive and thus well tested.</li>
</ol>

<p>Downsides include:</p>

<ol>
<li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a>. It's strict. Things like default namespace handling are easier in other libraries.</li>
<li>Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.</li>
<li>Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.</li>
</ol>

<p>If you are doing simple path selection, stick with <a href="http://effbot.org/zone/element-xpath.htm">ElementTree</a> ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.</p>

<p><strong>Sample of libxml2 XPath Use</strong></p>

<hr>

<pre><code>import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
    print "xpath query: wrong node set size"
    sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
    print "xpath query: wrong node set value"
    sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()
</code></pre>

<p><strong>Sample of ElementTree XPath Use</strong></p>

<hr>

<pre><code>from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
    print e.get('title').text</code></pre>

<hr>
