如何使用Python将大型xml文件转换为csv

时间:2016-02-10 08:13:47

标签: python xml-parsing

我想将一个非常大的XML文件转换为CSV格式,而不需要硬编码标记名。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

首先,您需要解析XML文件。这可以通过ElementTree API

完成

示例代码:

import xml.etree.ElementTree as ET
root = ET.parse('your_data.xml').getroot()
with open("output.csv", "w") as file:
    for child in root:
        print(child.tag, child.attrib)
        # naive example how you could save to csv line wise
        file.write(child.tag+";"+child.attrib)

There are also solutions to parse your XMLs directly as dictionary.

然后csv.DictWriter可用于将字典保存为CSV。