【发布时间】:2017-04-27 15:35:29
【问题描述】:
对于一个作业,我需要解析一个 200 万行的 XML 文件,并将数据输入到 MySQL 数据库中。由于我们使用带有 sqlite 的 python 环境作为类,我正在尝试使用 python 来解析文件。请记住,我只是在学习 python,所以一切都是新的!
我尝试了几次,但一直失败并感到沮丧。 为了提高效率,我只在少量完整的 XML 上测试我的代码,这里:
<pub>
<ID>7</ID>
<title>On the Correlation of Image Size to System Accuracy in Automatic Fingerprint Identification Systems</title>
<year>2003</year>
<booktitle>AVBPA</booktitle>
<pages>895-902</pages>
<authors>
<author>J. K. Schneider</author>
<author>C. E. Richardson</author>
<author>F. W. Kiefer</author>
<author>Venu Govindaraju</author>
</authors>
</pub>
第一次尝试
这里我成功地从每个标签中提取了所有数据,除非<authors>标签下有多个作者。我正在尝试遍历作者标签中的每个节点,计数,然后为这些作者创建一个临时数组,然后使用 SQL 将它们放入我的数据库中。我的作者数量是“15”,但显然只有 4 个!我该如何解决?
from xml.dom import minidom
xmldoc= minidom.parse("test.xml")
pub = xmldoc.getElementsByTagName("pub")[0]
ID = pub.getElementsByTagName("ID")[0].firstChild.data
title = pub.getElementsByTagName("title")[0].firstChild.data
year = pub.getElementsByTagName("year")[0].firstChild.data
booktitle = pub.getElementsByTagName("booktitle")[0].firstChild.data
pages = pub.getElementsByTagName("pages")[0].firstChild.data
authors = pub.getElementsByTagName("authors")[0]
author = authors.getElementsByTagName("author")[0].firstChild.data
num_authors = len(author)
print("Number of authors: ", num_authors )
print(ID)
print(title)
print(year)
print(booktitle)
print(pages)
print(author)
【问题讨论】: