我正在尝试解析OpenOffice ODS电子表格中的内容。ods格式本质上只是一个包含多个文档的zipfile。电子表格的内容存储在“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: ':'
发布于 2010-11-18 01:39:21
如果root.nsmap
包含table
名称空间前缀,那么您可以:
root.xpath('.//table:table', namespaces=root.nsmap)
findall(path)
接受{namespace}name
语法,而不是namespace:name
。因此,在将path
传递给findall()
之前,应该使用名称空间字典将其预处理为{namespace}name
表单。
发布于 2013-12-19 18:34:07
下面是获取XML文档中所有名称空间的方法(假设没有前缀冲突)。
当我预先知道名称空间URL是什么,并且只知道前缀时,我就会在解析XML文档时使用它。
doc = etree.XML(XML_string)
# Getting all the name spaces.
nsmap = {}
for ns in doc.xpath('//namespace::*'):
if ns[0]: # Removes the None namespace, neither needed nor supported.
nsmap[ns[0]] = ns[1]
doc.xpath('//prefix:element', namespaces=nsmap)
发布于 2018-08-30 18:29:05
如果XML文件中没有xmlns
定义,Etree将找不到带名称空间的元素。例如:
import lxml.etree as etree
xml_doc = '<ns:root><ns:child></ns:child></ns:root>'
tree = etree.fromstring(xml_doc)
# finds nothing:
tree.find('.//ns:root', {'ns': 'foo'})
tree.find('.//{foo}root', {'ns': 'foo'})
tree.find('.//ns:root')
tree.find('.//ns:root')
有时这就是你得到的数据。那么,如果没有名称空间,该怎么办呢?
我的解决方案是:添加一个。
import lxml.etree as etree
xml_doc = '<ns:root><ns:child></ns:child></ns:root>'
xml_doc_with_ns = '<ROOT xmlns:ns="foo">%s</ROOT>' % xml_doc
tree = etree.fromstring(xml_doc_with_ns)
# finds what you're looking for:
tree.find('.//{foo}root')
https://stackoverflow.com/questions/4210730
复制相似问题