使用Python将xml转csv
时间: 2023-03-01 22:45:02 浏览: 156
要将XML转换为CSV,可以使用Python中的模块,如lxml或pandas。
方法1:使用lxml
- 安装lxml:`pip install lxml`
- 代码示例:
```python
from lxml import etree
import csv
def xml2csv(xml_file, csv_file):
with open(xml_file, 'r') as f:
xml_content = f.read()
root = etree.XML(xml_content)
header = []
rows = []
for element in root.iter():
if element.tag == root.tag:
for sub_element in element:
row = []
if sub_element.tag not in header:
header.append(sub_element.tag)
for sub_sub_element in sub_element:
if sub_sub_element.tag not in header:
header.append(sub_sub_element.tag)
row.append(sub_sub_element.text)
rows.append(row)
with open(csv_file, 'w') as f:
writer = csv.writer(f)
writer.writerow(header)
for row in rows:
writer.writerow(row)
xml2csv('input.xml', 'output.csv')
```
方法2:使用pandas
- 安装pandas:`pip install pandas`
- 代码示例:
```python
import pandas as pd
def xml2csv(xml_file, csv_file):
xml_data = pd.read_xml(xml_file)
xml_data.to_csv(csv_file, index=None, header=True)
xml2csv('input.xml', 'output.csv')
```
阅读全文