Python、XML和遍历标记都不会产生任何值
我目前有一个Python程序,它打开一个XML文件,遍历标记并将内容打印到文本文件中Python、XML和遍历标记都不会产生任何值,python,xml,elementtree,Python,Xml,Elementtree,我目前有一个Python程序,它打开一个XML文件,遍历标记并将内容打印到文本文件中 import xml.etree.ElementTree as etree import xml.etree.ElementTree as ET import tkFileDialog #asks for the location of the file to open file = tkFileDialog.askopenfilename() #parse in the file tree = ET.par
import xml.etree.ElementTree as etree
import xml.etree.ElementTree as ET
import tkFileDialog
#asks for the location of the file to open
file = tkFileDialog.askopenfilename()
#parse in the file
tree = ET.parse(file)
root = tree.getroot()
#asks for the location/name of court file to save as
file = tkFileDialog.asksaveasfilename()
f = open(file, 'w')
f.write("\t\t\tReport: \n\n")
#this prints out all tags and text in the right order
iter_ = tree.getiterator()
for elem in iter_:
#print (elem.tag, elem.text)
f.write("\t")
f.write(elem.tag)
f.write(": \t\t")
f.write(str(elem.text))
f.write("\n")
f.close()
问题是XML文件中的一些标记没有任何用户输入,因此当程序迭代时,它不会在空间中放置任何标记,而不是将其留空
文本文件输出:
Crime Report:
crime_report: None
case_number: 090
victim_details: None
victim_first_name: j
victim_surname: j
officer_details: None
officer_name: j
officer_ID_number: j
witness_details: None
witness_first_name: j
witness_address: j
当前XML文件:
<crime_report>
<case_number caseno="unique identifier associated to the case">090
<victim_details>
<victim_first_name>j</victim_first_name>
<victim_surname>j</victim_surname>
</victim_details>
<officer_details>
<officer_name>j</officer_name>
<officer_ID_number>j</officer_ID_number>
</officer_details>
<witness_details>
<witness_first_name>j</witness_first_name>
<witness_address>j</witness_address>
</witness_details>
</case_number>
</crime_report>
我不知道如何迭代,使它们只显示为空,而不显示为无?您能在输出代码中添加一个条件吗?如果elem.text不是无:……谢谢,我不知道为什么我不想这么做!我想我认为这会更复杂。