I'm trying to parse content in an OpenOffice ODS spreadsheet. The ods format is essentially just a zipfile with a number of documents. The content of the spreadsheet is stored in 'content.xml'.
import zipfile
from lxml import etree
zf = zipfile.ZipFile('spreadsheet.ods')
root = etree.parse(zf.open('content.xml'))
The content of the spreadsheet is in a cell:
table = root.find('.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table')
We can also go straight for the rows:
rows = root.findall('.//{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-row')
The individual elements know about the namespaces:
>>> table.nsmap['table']
'urn:oasis:names:tc:opendocument:xmlns:table:1.0'
How do I use the namespaces directly in find/findall?
The obvious solution does not work.
Trying to get the rows from the table:
>>> 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: ':'
Etree won't find namespaced elements if there are no
xmlns
definitions in the XML file. For instance:Sometimes that is the data you are given. So, what can you do when there is no namespace?
My solution: add one.
Here's a way to get all the namespaces in the XML document (and supposing there's no prefix conflict).
I use this when parsing XML documents where I do know in advance what the namespace URLs are, and only the prefix.
If
root.nsmap
contains thetable
namespace prefix then you could:findall(path)
accepts{namespace}name
syntax instead ofnamespace:name
. Thereforepath
should be preprocessed using namespace dictionary to the{namespace}name
form before passing it tofindall()
.Maybe the first thing to notice is that the namespaces are defined at Element level, not Document level.
Most often though, all namespaces are declared in the document's root element (
office:document-content
here), which saves us parsing it all to collect innerxmlns
scopes.Then an element nsmap includes :
None
prefix (not always)If, as ChrisR mentionned, the default namespace is not supported, you can use a dict comprehension to filter it out in a more compact expression.
You have a slightly different syntax for xpath and ElementPath.
So here's the code you could use to get all your first table's rows (tested with:
lxml=3.4.2
) :