1

我收到了一个包含我需要的数据的 XML 文件,我需要将其转换为 CSV。

这应该很简单,但是 XML 的“重复单元”的子节点数并不总是相同的。

我正在努力解决的是如何最好地迭代每个子元素的子元素,直到没有更多子元素,并将其作为一个“行”返回。最终输出应该是一个字典列表(对于 CSV,每个“行”一个列表)。

举个例子

            <repeatingunit>
                <city>
                    <name>London</name>
                </city>
                <station>
                    <name>Southwark</name>
                    <tubeline>
                        <name>Jubilee</name>
                    </tubeline>
            </repeatingunit>
            <repeatingunit>
                <city>
                    <name>London</name>
                    <county>UK</county>
                <station>
                    <name>Mile End</name>
                </station>
            </repeatingunit>

这应该导致:

            {'city|name':'London','station|name':'Southwark','station|tubeline|name': 'Jubilee'},{'city|name':'London','city|country':'UK','station|name':'Mile End'}

我一直在使用 xml.etree.ElementTree 和 root.iter,我对循环很满意,但它的活力。

我尝试在这里使用多个嵌套列表的逻辑,但无济于事。有人可以指出我正确的方向并提出一种新方法吗?

我知道最后长度不同的字典对于写出 csv 并不理想,但我可以根据我想要的输出来处理它。

4

1 回答 1

0

递归解决方案怎么样?

def build_key(elem, key, result):
    key = key + '|' + elem.name
    if not elem.children:
        result[key] = elem.text

    else:
        for child in elem.children:
            build_key(child, key, result)

results = []
for unit in soup.find_all('repeatingunit'):
    result = {}
    for child in unit.children:
        build_key(child, '', result)
于 2016-12-08T17:50:49.510 回答