如何使用python将多个XML文件转换为csv? “测试” 文本文本。
上面是我的示例XML。需要使用ElementTree将此XML转换为CSV 演示:如何使用python将多个XML文件转换为csv? “测试” 文本文本。,python,xml,pandas,Python,Xml,Pandas,上面是我的示例XML。需要使用ElementTree将此XML转换为CSV 演示: <?xml version="1.0" encoding="UTF-8"?><document> <Task>"Test"</Task> <author Test="xxx" lang="EN" type="Twitter"/> <comments>Text Text Text Text. </comments&
<?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文件名。
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