如何在Python中从odt XML文件中提取数据?

2 投票
1 回答
1155 浏览
提问于 2025-04-17 20:17

我已经成功在Python中获取了odt格式的xml文件,但我不知道怎么提取这个xml文件里的数据。

有没有什么方法可以用来提取odt xml文件中的数据呢?

这是我用来提取odt xml文件的代码:

#!/usr/lib/python2.7

import sys, zipfile

if len(sys.argv) < 2:
    print "input.odt & output.xml"
    sys.exit(0)

content=""
myfile = zipfile.ZipFile(sys.argv[1])
listoffiles = myfile.infolist()
for s in listoffiles:
    if s.orig_filename == 'content.xml':
        fd = open(sys.argv[2],'w')
        content = myfile.read(s.orig_filename)
        fd.write(content)
        fd.close()

1 个回答

2

有没有什么方法可以提取odt文件的xml数据呢?

我猜你是想知道怎么解析这个xml文件的内容。如果是这样的话,我推荐你使用BeautifulSoup。BeautifulSoup主要是用来解析html的,但也可以调整一下来处理xml数据:

BS4:

from bs4 import BeautifulSoup

soup = Beautifulsoup(<xml file contents>, 'xml')

BeautifulSoup 3:

from BeautifulSoup import BeautifulStoneSoup

soup = BeautifulStoneSoup(<xml file contents>)

接下来你可以根据上面链接的文档来解析数据。

撰写回答