33

我正在尝试解析 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: ':'
4

4 回答 4

27

如果root.nsmap包含table命名空间前缀,那么您可以:

root.xpath('.//table:table', namespaces=root.nsmap)

findall(path)接受{namespace}name语法而不是namespace:name. 因此path,在将{namespace}name表单传递给findall().

于 2010-11-18T01:39:20.500 回答
14

也许首先要注意的是命名空间是在元素级别定义的,而不是文档级别。

但大多数情况下,所有命名空间都在文档的根元素(office:document-content此处)中声明,这样我们就无需解析它以收集内部xmlns范围。

然后元素 nsmap 包括:

  • 默认命名空间,带None前缀(不总是)
  • 所有祖先命名空间,除非被覆盖。

如果,正如 ChrisR 所提到的,默认命名空间不受支持,您可以使用字典推导以更紧凑的表达式将其过滤掉。

xpath 和ElementPath的语法略有不同 。


所以这里是你可以用来获取所有第一个表的行的代码(测试:)lxml=3.4.2

import zipfile
from lxml import etree

# Open and parse the document
zf = zipfile.ZipFile('spreadsheet.ods')
tree = etree.parse(zf.open('content.xml'))

# Get the root element
root = tree.getroot()

# get its namespace map, excluding default namespace
nsmap = {k:v for k,v in root.nsmap.iteritems() if k}

# use defined prefixes to access elements
table = tree.find('.//table:table', nsmap)
rows = table.findall('table:table-row', nsmap)

# or, if xpath is needed:
table = tree.xpath('//table:table', namespaces=nsmap)[0]
rows = table.xpath('table:table-row', namespaces=nsmap)
于 2015-02-24T16:08:13.930 回答
11

这是一种获取 XML 文档中所有名称空间的方法(假设没有前缀冲突)。

我在解析 XML 文档时使用它,我事先知道命名空间 URL 是什么,并且只知道前缀。

        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)
于 2013-12-19T18:34:06.740 回答
1

xmlns如果XML 文件中没有定义,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')
于 2018-08-30T18:29:05.407 回答