我对将内容从 .xml 转换为 .txt 感到困惑。我已经处理了 txt 到 xml 的转换,但是 xml 到 txt 的问题似乎更难。
应用程序应从子元素中获取所有值并将它们分配到列表中。问题是 xml 文件有多个根元素(知道这是无效格式)F.e:sample.xml 如下所示:
<row>
<col>One</col>
<col>Two</col>
<col>Three</col>
</row>
<row>
<col>John</col>
<col>Mark</col>
<col>Elise</col>
</row>
结果 sample.txt 应该如下所示:
One Two Three
John Mark Elise
在写这篇文章的过程中,我想到了一个想法,但它看起来很难看(尤其是从行中删除 col 标签)。对于从子元素 |col| 获取值,您有更好的想法吗?
我的代码:
def convert_xml_to_txt(self):
words_list = []
with open(self.filename) as fxml:
while True:
line = fxml.readline()
if line:
if line.startswith('<row'):
pass
else:
words_list.append(line[5:-7].strip()) #delete tags <col> from line
else:
self.generate_txt_file(words_list)
break
请您参考如下方法:
您可以使用几个库: 一个是 untangle,可以通过 pip 安装,例如 pip install untangle:
import untangle
obj = untangle.parse('path/to/file.xml')
或者您可以使用 xmltodict 有用的库:
import xmltodict
with open('path/to/file.xml') as fd:
doc = xmltodict.parse(fd.read())
有关更多信息,请参阅 This链接。
