在Python中使用lxml解析ODF

发布于 2024-12-04 18:14:26 字数 377 浏览 6 评论 0原文

我正在尝试解析 ODF 文件内的 content.xml。我已将文件读入字符串,并且得到了一个带有 lxml.etree 的树对象:

tree = etree.XML(string)

但现在我需要找到 text:a 或 text:h 的每个子元素。在上一个问题中我被告知可以使用 XPath。我尝试过,但每次都被卡住了。甚至找不到这些元素之一。

如果我尝试:

elem = tree.xpath('//text:p')
I just get a
XPathEvalError: Undefined namespace prefix

那么,如何以正确的顺序获得包含这两个子元素的列表,以便我可以迭代它们?

I'm trying to parse the content.xml inside a ODF-file. I've read the file into a string and i've got a tree object with lxml.etree:

tree = etree.XML(string)

But now I need to find every subelement that is text:a OR text:h. I've been told in previous question that I could use XPath. I've tried but got stuck every single time. Can't even find one of those elements.

If i try:

elem = tree.xpath('//text:p')

I just get a

XPathEvalError: Undefined namespace prefix

So how do I get a list with BOTH of thoose subelements in the right order so i can iterate over them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剩一世无双 2024-12-11 18:14:26

这是因为 text 是命名空间缩写,在 ODF 架构。尝试

tree.xpath('//text:a | //text:h',
           namespaces={'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'})

| 是集合并集运算符。另请参阅 LXML 文档

That's because text is a namespace abbreviation, defined in the ODF schema. Try

tree.xpath('//text:a | //text:h',
           namespaces={'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'})

| is the set union operator. See also LXML docs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文