<p>如果可以切换到<a href="http://codespeak.net/lxml/" rel="nofollow noreferrer">lxml</a>,下面是一种方法:</p>
<pre><code>import lxml.etree as le
root=le.XML(content)
result=[]
namespaces={'pre':'http://www.mysyte.com/foo'}
for record in root:
id=record.xpath('pre:id',namespaces=namespaces)[0]
name=record.xpath('pre:name',namespaces=namespaces)[0]
result.append({'code':id.text,'name':name.text})
print(result)
# [{'code': 'first', 'name': 'john'}, {'code': 'second', 'name': 'mike'}, {'code': 'third', 'name': 'albert'}]
</code></pre>
<p>从<a href="https://stackoverflow.com/questions/3366032/python-and-libxml2-how-to-iterate-in-xml-nodes-with-xpath/3371664#3371664">Dimitre Novatchev's XPath expression</a>开始构建,您可以这样做:</p>
<pre><code>id_name_nodes = iter(ctxt.xpathEval('/pre:records/pre:record/*[self::pre:id or self::pre:name]'))
ret_list=[]
for id,name in zip(id_name_nodes,id_name_nodes):
ret_list.append({'code':id.content,'name':name.content})
print(ret_list)
</code></pre>
<p>这个libxml2代码依赖于每个具有id和名称的记录。
如果缺少<code>id</code>或<code>name</code>,则<code>ret_list</code>将配对错误的id和名称,并以静默方式失败。在相同的情况下,lxml代码将引发一个错误。</p>