python - xml 文件每次迭代的新列表

标签 python xml python-3.x list elementtree

示例 XML 文件:

<main>
   <data>
      <some>111</some>
      <other>222</other>
      <more>333</more>
   </data>
   <data>
      <some>444</some>
      <other>555</other>
      <more>666</more>
   </data>
   <data>
      <some>777</some>
      <other>888</other>
      <more>999</more>
   </data>
</main>

我想为数据的每个子子项创建一个列表。例如:

1 = [111, 222, 333]
2 = [444, 555, 666]
3 = [777, 888, 999]

我想创建一个循环,迭代整个 XML 文件,然后创建一个存储下一组数据的新列表(不覆盖先前创建的列表)。

tree = et.parse(xml_file)
root = tree.getroot()

num = 0
for child in root:
    num = []
    num += 1
    for element in child:
        num.append(element.text)

我知道这段代码不起作用,但我希望它能让我了解我想要达到的目的。我不确定如何解决这个问题,正在寻找想法。

最佳答案

这里(没有使用外部库)

import xml.etree.ElementTree as ET

xml = '''<main>
   <data>
      <some>111</some>
      <other>222</other>
      <more>333</more>
   </data>
   <data>
      <some>444</some>
      <other>555</other>
      <more>666</more>
   </data>
   <data>
      <some>777</some>
      <other>888</other>
      <more>999</more>
   </data>
</main>'''

root = ET.fromstring(xml)
collected_data = []
for d in root.findall('.//data'):
    collected_data.append([d.find(x).text for x in ['some', 'other', 'more']])
print(collected_data)
# if the output needs to be a dict
collected_data = {idx + 1: entry for idx, entry in enumerate(collected_data)}
print(collected_data)

输出

[['111', '222', '333'], ['444', '555', '666'], ['777', '888', '999']]
{1: ['111', '222', '333'], 2: ['444', '555', '666'], 3: ['777', '888', '999']}

关于python - xml 文件每次迭代的新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57211213/

相关文章:

python - 是否可以使用带有 python 的默认互联网浏览器打开某些网址?

python - 使用 importlib.util 检查库时出错

python - 逗号出现在自定义 Ansible 查找插件返回的值中

xml - 如何对XML文件进行以下编辑?

xml - 如何运行 XSLT 文件?

python-3.x - Pandas groupby 然后为每个组添加新行

python - 将 lxml 输出传递给 BeautifulSoup

c# - 通过 linq 解析 xml

python - 我如何找到当前的分贝级别并将其设置为变量?

arrays - 将 3D numpy 数组转换为 3 个索引的列表