我正試圖解析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