【发布时间】:2015-11-19 18:10:40
【问题描述】:
我正在使用 xml.etree.ElementTree 模块来解析 XML 文件,将属性返回到列表中,然后将这些列表输入到 MySQL 数据库中(这最后一步我不担心,所以没有必要介绍在这里)。很简单,我目前能够这样做,但一次只能处理一个子节点。目标是使用多个子节点来执行此操作,而不管有多少子节点。这是一个示例文件:
<?xml version="1.0"?>
<catalog>
<book id="bk101" type="hardcover">
<info author="Gambardella, Matthew" title="XML Developer's Guide" genre="Computer" price="44.95" publish_date="2000-10-01" description="An in-depth look at creating applications
with XML." />
</book>
<book id="bk102" type="softcover">
<info author="Ralls, Kim" title="Midnight Rain" genre="Fantasy" price="5.95" publish_date="2000-10-01" description="A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world." />
</book>
<book id="bk101" type="softcover">
<info author="Corets, Eva" title="Maeve Ascendant" genre="Fantasy" price="5.95" publish_date="2000-11-17" description="After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society." />
</book>
</catalog>
我能够通过返回具有正确属性的列表来解析第一个书节点的正确属性,其中 id="bk101" 或最后一个书节点 id="bk103"。但是,当我需要返回多个列表(每个书节点和信息节点一个,因此在这种情况下总共有 6 个列表)时,我只为每个文件返回一个列表。
这是我的代码:
import xml.etree.ElementTree
book_attribute = ['id', 'type']
info_attribute = ['author', 'title', 'genre', 'price', 'publish_date', 'description']
class ApplicationClass(object): # define the only class in this file
def __init__(self):
self.ET = xml.etree.ElementTree.parse('file.xml').getroot()
self.bookNodes = self.ET.findall('book')
self.book_values_list = []
self.info_values_list = []
def get_book(self):
for bookNode in self.bookNodes:
self.book_values_list = [bookNode.get(i) for i in book_attribute]
return self.book_values_list
def get_info(self):
for bookNode in self.bookNodes:
for infoNode in bookNode.findall('info'):
self.info_values_list = [infoNode.get(i) for i in info_attribute]
return self.info_values_list
a = ApplicationClass()
a.get_book()
print(a.book_values_list)
a.get_info()
print(a.info_values_list)
所以我知道我的问题是每个函数只返回一个列表,因为我在函数末尾返回列表,然后在脚本末尾调用函数。我只是找不到合适的方法来实现我想要的结果。如果我不在脚本末尾运行我的函数,那么如何返回我正在寻找的多个列表?
【问题讨论】:
标签: python xml loops parsing elementtree