我正试图解析OpenOffice ODS电子表格中的内容。 ods格式基本上只是一个包含大量文档的zip文件。电子表格的内容存储在'content.xml'中。如何在lxml中使用find/findall来使用xml命名空间?
import zipfile
from lxml import etree
zf = zipfile.ZipFile('spreadsheet.ods')
root = etree.parse(zf.open('content.xml'))
电子表格的内容是在一个单元格:
table = root.find('.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table')
我们也可以直行行:
rows = root.findall('.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-row')
各个元素知道的命名空间:
>>> table.nsmap['table']
'urn:oasis:names:tc:opendocument:xmlns:table:1.0'
怎么办我直接在find/findall中使用命名空间?
显而易见的解决方案不起作用。
试图从表中的行:
>>> root.findall('.//table:table')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1792, in lxml.etree._ElementTree.findall (src/lxml/lxml.etree.c:41770)
File "lxml.etree.pyx", line 1297, in lxml.etree._Element.findall (src/lxml/lxml.etree.c:37027)
File "/usr/lib/python2.6/dist-packages/lxml/_elementpath.py", line 225, in findall
return list(iterfind(elem, path))
File "/usr/lib/python2.6/dist-packages/lxml/_elementpath.py", line 200, in iterfind
selector = _build_path_iterator(path)
File "/usr/lib/python2.6/dist-packages/lxml/_elementpath.py", line 184, in _build_path_iterator
selector.append(ops[token[0]](_next, token))
KeyError: ':'
您是否尝试过使用Python API OpenOffice的处理电子表格? – jfs 2010-11-18 01:41:45
您好我正在使用etree.QName来访问名称空间的元素和属性。它在命名空间字典的帮助下是一个整洁的方式,它也适用于find和findall方法。有关更多信息,请参阅:http://lxml.de/tutorial.html#namespaces – 2015-12-19 10:51:40