首页 > 解决方案 > 我将如何创建一个循环,为 .xml 文件中的每个孩子创建一个新元组

问题描述

所以对于我的项目,我需要获取一个 xml 文件,在 Python 中解析它,然后创建多个并行数组。我想出了如何制作一个包含所有孩子的大元组。现在我只需要想办法将它们分解成单独的元组。我认为最简单的方法是做一个 for 循环。但是,我遇到了麻烦。因此,如果我有一个 CD 列表及其信息,我想创建一个循环,将每张 CD 及其信息放入一个元组中。我该怎么办?

import xml.etree.ElementTree as ET


def get_xml_file():
    tree = ET.parse('cd_catalog.xml')
    return tree


def get_root(tree):
    root = tree.getroot()
    return root

def find_cd(tree):
    cd = tree.findall('.//CD')
    return cd


def build_cd_array(tree,root,cd):
    for x in range(len(cd)):
        array = [tuple(c.text for c in list(cd)) for cd in     root.findall('CD')
    print(array)






def main():
    tree = get_xml_file()
    root = get_root(tree)
    cd = find_cd(tree)
    build_cd_array(tree,root,cd)


main()

标签: pythonarraysxmltuples

解决方案


推荐阅读