擅长:python、mysql、java
<p>您可以使用<code>xpath</code>来找到<code>packitem</code>,然后再次调用<code>xpath</code>(或如下所述<code>findtext</code>)来找到<code>duration</code>和{<cd6>}。多次调用<code>xpath</code>可能不会太快,但它是有效的。在</p>
<pre><code>import lxml.etree as ET
content = '''<pack xmlns="http://ns.qubic.tv/2010/item">
<packitem>
<duration>520</duration>
<max_count>14</max_count>
</packitem>
<packitem>
<duration>12</duration>
</packitem>
</pack>
'''
def make_int(text):
try:
return int(text)
except TypeError:
return None
namespaces = {'ns' : 'http://ns.qubic.tv/2010/item'}
doc = ET.fromstring(content)
result = [tuple([make_int(elt.findtext(path, namespaces = namespaces))
for path in ('ns:duration', 'ns:max_count')])
for elt in doc.xpath('//ns:packitem', namespaces = namespaces) ]
print(result)
# [(520, 14), (12, None)]
</code></pre>
<p>另一种方法是使用SAX解析器。这可能会快一点,但需要更多的代码,如果XML不是很大,那么速度差异可能就不重要了。在</p>