我有一个问题。我试图将我的所有发布数据附加到xml文件中,但它总是覆盖。我在下面解释我的代码。
def some(request):
if request.method == 'POST':
location_name = request.POST.get('lname')
rname = request.POST.get('rname')
seat = request.POST.get('seat')
projector = request.POST.get('projector')
video = request.POST.get('video')
root = ET.Element("roomlist")
doc = ET.SubElement(root, "locationname", name=location_name)
doc1 = ET.SubElement(doc, "roomid", name="1234")
ET.SubElement(doc1, "roomname", name=rname).text = rname
ET.SubElement(doc1, "noseats", name=seat).text = seat
ET.SubElement(doc1, "projectorscreen", name=projector).text = projector
ET.SubElement(doc1, "videoconf", name=video).text = video
tree = ET.ElementTree(root)
tree.write("filename.xml")
return render(request, 'booking/bmr.html', {})
在这里我需要当用户提交表单时,所有数据都会附加到现有的xml文件中,但在我的情况下,每次都会覆盖它。请帮我解决这个问题。
答案 0 :(得分:0)
您需要创建数据并附加到文件:
root = tree.getroot()
xmlstr = ET.tostring(root, 'utf-8', method='xml')
with open("filename.xml", "a") as myfile:
myfile.write(xmlstr)
所以我要做的是创建树(你的代码)并转换为字符串(tostring()
),然后将此字符串附加到文件中:)