gpt4 book ai didi

python - 如何在 lxml 中使用带有 find/findall 的 xml 命名空间?

转载 作者:IT老高 更新时间:2023-10-28 22:21:41 25 4
gpt4 key购买 nike

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

最佳答案

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

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

findall(path) 接受 {namespace}name 语法而不是 namespace:name。因此,在将 path 传递给 findall() 之前,应该使用命名空间字典对 {namespace}name 表单进行预处理。

关于python - 如何在 lxml 中使用带有 find/findall 的 xml 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4210730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com