【发布时间】:2010-11-18 01:07:30
【问题描述】:
我正在尝试解析 OpenOffice ODS 电子表格中的内容。 ods 格式本质上只是一个包含许多文档的 zip 文件。电子表格的内容存储在“content.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 for OpenOffice 来处理电子表格?
-
您好,我正在使用 etree.QName 通过命名空间访问元素和属性。在命名空间字典的帮助下,它是一种巧妙的方式,它也适用于 find 和 findall 方法。更多信息请参考:lxml.de/tutorial.html#namespaces
标签: python xml lxml xml-namespaces elementtree