#coding:utf-8importxml.dom.minidom,csvfromtkinterimport*deffc(): ifinput.get() ==""andinput2.get() ==""andlabel_input.get() ==""andkey_input.get() =="": txt.insert(END, "请填写相关数据"+"\n") elifinput.get() =="": txt.insert(END, "xml文件名不能为空"+"\n") elifinput2.get() =="": txt.insert(END, "csv文件名不能为空"+"\n") eliflabel_input.get() =="": txt.insert(END, "标签名不能为空"+"\n") elifkey_input.get() =="": txt.insert(END, "字段名不能为空"+"\n") else: dom=xml.dom.minidom.parse(input.get()+".xml") root=dom.documentElementlista= [] print(len(root.getElementsByTagName(label_input.get()))) foriinrange(len(root.getElementsByTagName(label_input.get()))): test_case=root.getElementsByTagName(label_input.get())[i] name_list=test_case.getAttribute(key_input.get()) txt.insert(END, name_list+"\n") lista.append(test_case.getAttribute(key_input.get())) print(name_list) withopen(input2.get()+".csv", "a", newline='') asf: writer=csv.writer(f) writer.writerow(["读取到的值"]) row=listaforrinrow: writer.writerow([r]) windos=Tk() windos.geometry("600x500")#设置gui窗口大小windos.title("将xml文件中需要的数据读取到csv中")#gui窗口title名button=Button(windos,text="确定",command=fc)#按钮设置名字,按钮执行方法button.place(relx=0.85,rely=0.8,relwidth=0.1,relheight=0.1) label=Label(windos,text="标签名")#gui页面title名称label.place(relx=-0.2,rely=0.01,relwidth=0.5,relheight=0.05) label_input=Entry(windos) label_input.place(relx=0.1,rely=0.01,relwidth=0.15,relheight=0.05) key=Label(windos,text="字段名")#gui页面title名称key.place(relx=-0.2,rely=0.08,relwidth=0.5,relheight=0.05) key_input=Entry(windos) key_input.place(relx=0.1,rely=0.08,relwidth=0.15,relheight=0.05) la=Label(windos,text="请输入xml文件名")#gui页面title名称la.place(relx=0.35,rely=0.05,relwidth=0.3,relheight=0.05) input=Entry(windos)#输入框设置input.place(relx=0.35,rely=0.1,relwidth=0.3,relheight=0.05) la2=Label(windos,text="请输入csv文件名")#gui页面title名称la2.place(relx=0.1,rely=0.15,relwidth=0.8,relheight=0.05) input2=Entry(windos)#输入框设置input2.place(relx=0.35,rely=0.2,relwidth=0.3,relheight=0.05) la3=Label(windos,text="读取到的数据")#gui页面title名称la3.place(relx=0.1,rely=0.25,relwidth=0.8,relheight=0.05) txt=Text(windos)#gui输出页面txt.place(relx=0.25,rely=0.3,relwidth=0.5,relheight=0.5) windos.mainloop()#启动#if __name__ == '__main__':# fc()
XML文件:这里支持读取某个标签名和标签内容例如<testcase>中的name字段
<testcaseinternalid="73748"name="tci_setopt (9600 ,8 , ,1)"><node_order><![CDATA[1023]]></node_order><externalid><![CDATA[6751]]></externalid><version><![CDATA[1]]></version><execution_type><![CDATA[1]]></execution_type><importance><![CDATA[2]]></importance><estimated_exec_duration></estimated_exec_duration><status>1</status><is_open>1</is_open><active>1</active></testcase>