在ElementTree python中从XML数据集创建列表列表



我有个问题。如何在ElemenTree python中从xml数据集创建列表列表?例如,我有一个数据集:

<data>
<article>
<author> Tony </author>
</article>
<article>
<author> Andy </author>
<author> John </author>
</article>
<article>
<author> Paul </author>
<author> leon </author>
</article>
</data>

有一个特定的功能,如:

tree = ET.parse('data.xml')
root = tree.getroot()
for author in root.iter('author'):
print(author.text, author.attrib['pid'])

它将在单个列表CCD_ 1中查找并显示数据集中的所有作者。我如何改进上面的代码,以便在列表[[Tony], [Andy, John], [Paul, Leon]]中获得结果作者?也许有一个特定的功能来执行这个?

一个线性可以实现神奇的

import xml.etree.ElementTree as ET
xml = '''<data>
<article>
<author> Tony </author>
</article>
<article>
<author> Andy </author>
<author> John </author>
</article>
<article>
<author> Paul </author>
<author> leon </author>
</article>
</data>'''
root = ET.fromstring(xml)
authors = [[aut.text for aut in art.findall('author')] for art in root.findall('./article')]
print(authors)

输出

[[' Tony '], [' Andy ', ' John '], [' Paul ', ' leon ']]

我找到了解决方案。这很简单。只需创建嵌套循环,用特定标签从root迭代child,然后从child迭代child2

author_connection = []
for child in root:

conn = []
author_connection.append(conn)
for child2 in child.iter('author'):
conn.append(child2.text)

输出为

[[Tony], [Andy, John], [Paul, Leon]]