用Python解析XML时处理多个节点

2024-06-28 15:10:23 发布

您现在位置:Python中文网/ 问答频道 /正文

对于赋值,我需要解析一个200万行的XML文件,并将数据输入MySQL数据库。因为我们使用的是python环境和sqlite作为类,所以我尝试使用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>标记下有多个作者。我尝试循环遍历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)

Tags: 标记iddatatitle作者xmlpagesyear
1条回答
网友
1楼 · 发布于 2024-06-28 15:10:23

请注意,这里得到的是第一作者的字符数,因为代码将结果限制为仅第一作者(索引0),然后得到其长度:

author = authors.getElementsByTagName("author")[0].firstChild.data
num_authors = len(author)
print("Number of authors: ", num_authors )

只是不要将结果限制为所有作者:

author = authors.getElementsByTagName("author")
num_authors = len(author)
print("Number of authors: ", num_authors )

您可以使用列表理解获取列表中的所有作者姓名,而不是作者元素:

author = [a.firstChild.data for a in authors.getElementsByTagName("author")]
print(author)
# [u'J. K. Schneider', u'C. E. Richardson', u'F. W. Kiefer', u'Venu Govindaraju']

相关问题 更多 >