Python—如何使用xml.etree.ElementTree为正在迭代的每个xml节点返回列表?

Python—如何使用xml.etree.ElementTree为正在迭代的每个xml节点返回列表?,python,xml,loops,parsing,elementtree,Python,Xml,Loops,Parsing,Elementtree,我正在使用xml.etree.ElementTree模块解析xml文件,将属性返回到列表中,然后将这些列表输入MySQL数据库(我不担心这最后一步,所以这里不需要介绍)。非常简单,我目前可以这样做,但一次只能为一个子节点。目标是对多个子节点执行此操作,而不管有多少子节点。以下是一个示例文件: <?xml version="1.0"?> <catalog> <book id="bk101" type="hardcover">

我正在使用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>

所以我知道我的问题是每个函数只返回一个列表,因为我在函数末尾返回列表,然后在脚本末尾调用函数。我就是找不到合适的方法来达到我想要的结果。如果我没有在脚本末尾运行我的函数,那么如何返回我要查找的多个列表?

这一行是您的问题:

self.book_values_list = [bookNode.get(i) for i in book_attribute]
该行将用新列表替换现有列表。但这条线在循环中,这意味着每次通过循环时,都会丢失先前处理过的内容

我想你想要这个:

self.book_values_list.append([bookNode.get(i) for i in book_attribute])
使用
.append()
而不是
=
将使变量中插入更多内容。最终,您将得到一个列表列表,如下所示:

[['bk101', 'hardcover'], ['bk102', 'softcover'], ['bk101', 'softcover']]
您的另一个方法/循环也有同样的问题-您为变量分配了一个新列表,而不是将一个新列表插入到现有列表中

[['bk101', 'hardcover'], ['bk102', 'softcover'], ['bk101', 'softcover']]