当我尝试将数据添加到以前保存的xml文件时,我的格式化了。我已经编写了一种方法,可以将数据添加到现有的xml中,另一种方法在保存之后对其应用漂亮的打印(它使用minidom,因为我无法生成lxml
&# 39; s方法工作)。
问题是它适用于第一次迭代(当我第一次添加数据时,就是我创建了一个新文件)。当我向已经创建的文件添加数据时,只有最新的数据格式正确,所有以前的数据都没有格式化。
如何让它发挥作用?我想它可能正在使用lxml库,但我在尝试使用它时会遇到异常。
将数据添加到xml的代码:
def AddDataToExistingXML(file_path, data_to_be_added):
try:
xml = ET.parse(file_path)
root = xml.getroot()
formatted_date_time = DownloadData.ConvertFullDateToISO(data_to_be_added['Date'] + ' ' + data_to_be_added['Time'])
doc = ET.SubElement(root, "ChildElem", ID=data_to_be_added['ID'])
ET.SubElement(doc, "Data").text = formatted_date_time
if 'Occurences' in data_to_be_added:
ET.SubElement(doc, "Occurences").text = data_to_be_added['Occurences']
else:
ET.SubElement(doc, "Occurences").text = ' xsi:nil=' + '\"' + 'true' + '\"' + ' '
Array = ET.SubElement(doc, "Array")
for i in range (1, 21):
ET.SubElement(Array, 'A').text = data_to_be_added['Number' + str(i)]
xmlstr = ET.tostring(root)
string = etree.tostring(etree.fromstring(xmlstr)).decode()
with open(file_path, "w") as f:
f.write(string)
except FileNotFoundError:
print('File {file_path} has not been found! New file {file_path} will be created.'.format(file_path=file_path))
DownloadData.AddDataToNewXML(file_path, data_to_be_added)
格式化xml的代码:
def MakePrettyXML(file_path):
xml = ET.parse(file_path)
root = xml.getroot()
xmlstr = ET.tostring(root)
dom = minidom.parseString(xmlstr)
pretty_xml = dom.toprettyxml().encode('utf-8')
prety_xml_unicode = etree.tostring(etree.fromstring(pretty_xml), xml_declaration=True, encoding='utf-8').decode()
with open(file_path, "w", "utf-8") as f:
f.write(prety_xml_unicode)
输出示例:
<?xml version'1.0' encoding='utf-8'?>
<RootElem>
<ChildElem ID="9360">
<Date>2016-03-18T14:00:00</Date>
<Occurences>5</Occurences>
<Array>
<A>9</A>
<A>6</A>
<A>51</A>
<A>78</A>
<A>66</A>
<A>37</A>
<A>7</A>
<A>30</A>
<A>54</A>
<A>38</A>
<A>43</A>
<A>11</A>
<A>16</A>
<A>52</A>
<A>76</A>
<A>29</A>
<A>28</A>
<A>48</A>
<A>31</A>
<A>5</A>
</Array>
</ChildElem>
<ChildElem ID="9360">
<Date>2016-03-18T14:00:00</Date>
<Occurences>5</Occurences>
<Array>
<A>9</A>
<A>6</A>
<A>51</A>
<A>78</A>
<A>66</A>
<A>37</A>
<A>7</A>
<A>30</A>
<A>54</A>
<A>38</A>
<A>43</A>
<A>11</A>
<A>16</A>
<A>52</A>
<A>76</A>
<A>29</A>
<A>28</A>
<A>48</A>
<A>31</A>
<A>5</A>
</Array>
</ChildElem>
</RootElem>