<?xml version="1.0" encoding="UTF-8"?><document>
<Task>"Test"</Task>
<author Test="xxx" lang="EN" type="Twitter"/>
<comments>Text Text Text Text.
</comments>
</document>
上面是我的示例XML。需要转换此XML并使用
写入CSV答案 0 :(得分:1)
使用 ElementTree
<强>演示:强>
from xml.etree import ElementTree as ET
import os
import csv
res = []
for filename in os.listdir(path): #Check Dir For file
if filename.endswith('.xml'): #Check if extension is '.xml'
filePath = os.path.join(path, filename)
x = ET.parse(filePath) #Read xml using 'ET.parse'
res.append([x.find("Task").text.strip(), x.find("author").attrib["type"], x.find("comments").text.strip()]) #Get required values.
with open(r"C:\Users\zk0h098\Desktop\testFiles\A.csv", "w") as infile:
writer = csv.writer(infile, delimiter=",")
writer.writerow(["Task", "Author", "Comments"]) #Write Header
for line in res:
writer.writerow(line) #Write content